1. What is JavaScript, and what are its primary uses?
JavaScript is a high-level, dynamically typed programming language that is primarily used for creating interactive web pages and web applications. It runs on the client-side (in the user’s web browser) and server-side (using Node.js). JavaScript allows developers to add dynamic behavior, validate forms, communicate with servers, and manipulate the content of web pages.
Code Example:
// Example of client-side JavaScript
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!"); // Display an alert when the button is clicked
});
2. What is the difference between let
, var
, and const
in JavaScript?
In JavaScript, let
, var
, and const
are used to declare variables, but they have different scoping and reassignment rules. var
is function-scoped and can be reassigned and redeclared. let
is block-scoped and can be reassigned but not redeclared. const
is also block-scoped but cannot be reassigned or redeclared, making it useful for values that shouldn’t change.
Code Example:
var x = 10; // Function-scoped, can be reassigned and redeclared
let y = 20; // Block-scoped, can be reassigned but not redeclared
const z = 30; // Block-scoped, cannot be reassigned or redeclared
if (true) {
var x = 40; // Reassigns the global x variable
let y = 50; // Creates a new block-scoped y variable
// const z = 60; // Error: Cannot redeclare a const variable
}
console.log(x); // Output: 40
console.log(y); // Output: 20 (block-scoped y is not accessible here)
console.log(z); // Output: 30
3. How do you declare and initialize an array in JavaScript?
In JavaScript, an array is a collection of elements that can be of any data type. You can declare and initialize an array using square brackets []
, separating elements with commas. Alternatively, you can use the Array
constructor to create an array.
Code Example:
// Declaring and initializing an array using square brackets
const fruits = ["apple", "banana", "orange"];
// Declaring an array using the Array constructor
const numbers = new Array(1, 2, 3, 4, 5);
// Accessing array elements
console.log(fruits[0]); // Output: "apple"
console.log(numbers[3]); // Output: 4
4. Explain the concept of hoisting in JavaScript.
Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their respective scopes during the compilation phase, before the code is executed. This means that regardless of where variables and functions are declared in the code, they are treated as if they are declared at the beginning of their scope.
Code Example:
console.log(x); // Output: undefined
var x = 10;
console.log(greet()); // Output: "Hello, world!"
function greet() {
return "Hello, world!";
}
In this example, the variable x
is hoisted but not initialized, so it outputs undefined
. The function greet
is also hoisted, allowing it to be called before its actual declaration in the code.
5. What are the different data types in JavaScript?
JavaScript has several built-in data types, which can be categorized into primitive data types and non-primitive data types. The primitive data types are numbers, strings, booleans, null, undefined, and symbol. The non-primitive data type is object, which includes arrays, functions, and custom objects.
Code Example:
// Primitive data types
let num = 10;
let str = "Hello";
let bool = true;
let nullValue = null;
let undef = undefined;
let sym = Symbol("unique");
// Non-primitive data type (object)
let obj = { name: "John", age: 30 };
let arr = [1, 2, 3];
let func = function() { console.log("I'm a function"); };
console.log(typeof num); // Output: "number"
console.log(typeof str); // Output: "string"
console.log(typeof bool); // Output: "boolean"
console.log(typeof nullValue); // Output: "object" (a known bug in JavaScript)
console.log(typeof undef); // Output: "undefined"
console.log(typeof sym); // Output: "symbol"
console.log(typeof obj); // Output: "object"
console.log(typeof arr); // Output: "object"
console.log(typeof func); // Output: "function"
6. What is the difference between null
and undefined
?
In JavaScript, both null
and undefined
represent the absence of a value, but they have different meanings. undefined
is a primitive value that is automatically assigned to variables that have been declared but not initialized or to function parameters that have not been passed a value. null
, on the other hand, is an explicit value that represents a deliberate non-value or absence of any object value.
Code Example:
let undefinedVar;
let nullVar = null;
console.log(undefinedVar); // Output: undefined
console.log(nullVar); // Output: null
console.log(typeof undefinedVar); // Output: "undefined"
console.log(typeof nullVar); // Output: "object" (a known bug in JavaScript)
7. How do you create a function in JavaScript?
In JavaScript, you can create functions using the function
keyword followed by the function name, a list of parameters (optional) enclosed in parentheses, and the function body enclosed in curly braces. Functions can be defined using function declarations or function expressions.
Code Example:
// Function declaration
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Function expression
const square = function(num) {
return num * num;
};
// Arrow function
const multiply = (a, b) => a * b;
greet("John"); // Output: "Hello, John!"
console.log(square(5)); // Output: 25
console.log(multiply(3, 4)); // Output: 12
8. What is the purpose of the typeof
operator?
The typeof
operator in JavaScript is used to determine the data type of a value or expression. It returns a string indicating the type of the operand, such as “number”, “string”, “boolean”, “undefined”, “object”, “function”, or “symbol”.
Code Example:
console.log(typeof 42); // Output: "number"
console.log(typeof "Hello"); // Output: "string"
console.log(typeof true); // Output: "boolean"
console.log(typeof undefined); // Output: "undefined"
console.log(typeof null); // Output: "object" (a known bug in JavaScript)
console.log(typeof []); // Output: "object"
console.log(typeof {}); // Output: "object"
console.log(typeof function(){}); // Output: "function"
9. Explain what a callback function is.
A callback function is a function that is passed as an argument to another function and is invoked inside the outer function to complete some kind of action or routine. Callbacks are commonly used in asynchronous programming, where one function needs to wait for another function to complete before executing.
Code Example:
function fetchData(url, callback) {
// Simulating an asynchronous operation
setTimeout(() => {
const data = { id: 1, name: "John" };
callback(data);
}, 1000);
}
function processData(data) {
console.log(`Received data: ${JSON.stringify(data)}`);
}
fetchData("https://api.example.com/data", processData);
// Output (after 1 second): "Received data: {"id":1,"name":"John"}"
10. What is the difference between ==
and ===
?
In JavaScript, ==
and ===
are both comparison operators used to compare values, but they have different behaviors. The ==
operator performs type coercion, which means it attempts to convert the operands to a common type before comparing them. The ===
operator, on the other hand, performs a strict comparison without type coercion, ensuring that both the value and the type of the operands are equal.
Code Example:
console.log(1 == "1"); // Output: true (type coercion)
console.log(1 === "1"); // Output: false (strict comparison)
console.log(0 == false); // Output: true (type coercion)
console.log(0 === false); // Output: false (strict comparison)
console.log(null == undefined); // Output: true (type coercion)
console.log(null === undefined); // Output: false (strict comparison)
11. How do you add an element to an array?
In JavaScript, there are several methods to add elements to an array. The most common methods are push()
, which adds one or more elements to the end of the array, and unshift()
, which adds one or more elements to the beginning of the array. You can also use the spread operator (...
) or the concat()
method to combine arrays.
Code Example:
const fruits = ["apple", "banana"];
// Adding an element to the end of the array using push()
fruits.push("orange");
console.log(fruits); // Output: ["apple", "banana", "orange"]
// Adding an element to the beginning of the array using unshift()
fruits.unshift("grape");
console.log(fruits); // Output: ["grape", "apple", "banana", "orange"]
// Adding elements using the spread operator
const moreFruits = ["kiwi", "mango"];
const combinedFruits = [...fruits, ...moreFruits];
console.log(combinedFruits); // Output: ["grape", "apple", "banana", "orange", "kiwi", "mango"]
// Adding an element at a specific index
fruits.splice(2, 0, "pear");
console.log(fruits); // Output: ["grape", "apple", "pear", "banana", "orange"]