JavaScript Basics with Examples:

  1. Basic Syntax
  • Variables: let x = 10;
  • Constants: const PI = 3.14;
  • Print: console.log("Hello, World!");
  • Comments: Single-line // This is a comment, Multi-line /* This is a multi-line comment */

 

  1. Data Types
  • Numbers: let x = 42;
  • Strings: let greeting = "Hello";
  • Booleans: let isHappy = true;
  • Null: let emptyVar = null;
  • Undefined: let notDefined;

 

  1. String Manipulation
  • Concatenation: 'Hello' + ' ' + 'World'
  • Template literals: `Hello, ${name}!`
  • Length: 'Hello'.length
  • Upper / Lower: 'Hello'.toUpperCase() / 'Hello'.toLowerCase()

 

  1. Arrays
  • Initialization: let myArray = [1, 2, 3];
  • Access: myArray[0]
  • Append: myArray.push(4);
  • Remove: myArray.splice(0, 1);
  • Length: myArray.length
  • Slice: myArray.slice(1, 3)

 

  1. Objects
  • Initialization: let myObj = {a: 1, b: 2, c: 3};
  • Access: myObj.a or myObj['a']
  • Set: myObj.d = 4;
  • Remove: delete myObj.a;

 

  1. Conditionals
  • if: if (x > 10) { ... }
  • else if: else if (x > 5) { ... }
  • else: else { ... }

 

  1. Loops
  • For: for (let i = 0; i < 5; i++) { ... }
  • While: while (x < 10) { ... }
  • For…of: for (const item of myArray) { ... }
  • For…in: for (const key in myObj) { ... }

 

  1. Functions
  • Definition: function myFunction(arg1, arg2) { ... }
  • Arrow functions: const myFunction = (arg1, arg2) => { ... }
  • Call: myFunction(1, 2);
  • Return: return result;

 

  1. Classes
  • Definition: class MyClass { ... }
  • Constructor: constructor(attr1, attr2) { ... }
  • Methods: myMethod(arg) { ... }
  • Inheritance: class ChildClass extends ParentClass { ... }

 

  1. Promises
  • Creation: new Promise((resolve, reject) => { ... });
  • Chaining: myPromise.then(result => { ... }).catch(error => { ... });
  • Async / Await:
				
					async function myFunction() {
    try {
        const result = await myPromise;
    } catch (error) {
        // Handle error
    }
}
				
			
  1. DOM Manipulation
  • Select element: const el = document.querySelector("#myId");
  • Change content: el.textContent = "New content";
  • Add class: el.classList.add("my-class");
  • Remove class: el.classList.remove("my-class");
  • Set attribute: el.setAttribute("data-custom", "value");
  • Get attribute: el.getAttribute("data-custom");
  • Add event listener: el.addEventListener("click", eventHandlerFunction);


  1. AJAX (Fetch API)

GET request:

				
					fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

				
			

POST request:

				
					fetch("https://api.example.com/data", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    key1: "value1",
    key2: "value2"
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

				
			
  1. Destructuring
  • Arrays: const [a, b] = [1, 2];
  • Objects: const {a, b} = {a: 1, b: 2};
 
  1. Spread Operator
  • Arrays: const newArray = [...oldArray, newValue];
  • Objects: const newObj = {...oldObj, newKey: newValue};
 
  1. Modules
  • Export: export const myVar = 42; / export function myFunc() { ... }
  • Import: import { myVar, myFunc } from "./myModule.js";

Here are some common JavaScript interview questions:

What is JavaScript, and why is it used?

JavaScript is a high-level, interpreted programming language primarily used for adding interactivity, dynamic content, and manipulating the DOM on web pages. It is a core technology of the web, along with HTML and CSS.

What are the differences between var, let, and const in JavaScript?

‘var’ is function-scoped, while ‘let’ and ‘const’ are block-scoped. ‘const’ variables cannot be reassigned after being declared, while ‘var’ and ‘let’ can.

Can you explain hoisting in JavaScript?

Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their containing scope during the compilation phase. This allows variables and functions to be used before they are declared in the code.

What is a closure, and how do you use it in JavaScript?

A closure is a function that has access to its own scope, its outer (enclosing) function’s scope, and the global scope. Closures enable data encapsulation and help create private variables.

What are the different types of JavaScript data types?

JavaScript data types include String, Number, Boolean, Object, Function, Array, Null, and Undefined.

What is the difference between == and === in JavaScript?

‘==’ checks for loose equality and performs type coercion, while ‘===’ checks for strict equality without performing type coercion.

What is an arrow function, and how is it different from a regular function?

Arrow functions are a concise syntax for writing function expressions. They provide implicit ‘return’ for single-line expressions and do not bind their own ‘this’, ‘arguments’, ‘super’, or ‘new.target’.

What are JavaScript promises, and how do you use them?

A Promise is a JavaScript object representing the eventual completion or failure of an asynchronous operation. Promises have methods like ‘then()’ and ‘catch()’ for handling the resolution or rejection.

What is the event loop in JavaScript, and how does it work?

The event loop is a mechanism that continuously checks the message queue for tasks and executes them. It allows JavaScript to execute code asynchronously without blocking the main thread.

What are the different ways to create an object in JavaScript?

Different ways to create an object in JavaScript include object literal, constructor function, Object.create(), and ES6 classes.

What is the prototype in JavaScript, and how is it used in inheritance?

The prototype is an object shared by all instances of a constructor function. It is used for inheritance, enabling the sharing of methods and properties across instances without duplicating code.

How do you add or remove elements from an array in JavaScript?

Use ‘push()’ and ‘unshift()’ to add elements, and ‘pop()’ and ‘shift()’ to remove elements from an array.

Explain the differences between forEach, map, and reduce array methods.

‘forEach’ iterates over an array and executes a callback function for each element.

‘map’ creates a new array by applying a callback function to each element. ‘reduce’ iterates over an array and accumulates a single value based on the return value of a callback function.

What is the difference between a callback function and a promise?

A callback function is a function passed as an argument to another function, to be executed later. A promise is an object representing the eventual completion or failure of an asynchronous operation, allowing for better handling of asynchronous code.

What are some techniques for handling asynchronous code in JavaScript?

Techniques for handling asynchronous code include callbacks, promises, and async/await.

How do you handle exceptions with try, catch, and finally in JavaScript?

Use ‘try’ to wrap the code that might throw an exception, ‘catch’ to handle the exception, and ‘finally’ to execute code regardless of whether an exception occurred.

What is the difference between call, apply, and bind in JavaScript?

‘call’, ‘apply’, and ‘bind’ are methods used to set the ‘this’ value of a function. ‘call’ accepts a list of arguments, ‘apply’ accepts an array of arguments, and ‘bind’ returns a new function with the ‘this’ value and any provided arguments set.

How do you implement and use modules in JavaScript?

  1. Modules are self-contained pieces of code that can be imported and exported using ‘import’ and ‘export’ statements. They help in organizing and managing code by separating concerns and reducing global scope pollution.

What is the difference between a synchronous and an asynchronous function?

A synchronous function blocks the execution of other code until it finishes, while an asynchronous function allows other code to execute while it completes its task.

Explain event delegation in JavaScript and why it is useful.

Event delegation is a technique that involves attaching a single event listener to a parent element, to handle events from its child elements. This reduces the number of event listeners, improving performance and memory usage.

Social Share: