This repository is a comprehensive collection of JavaScript interview questions and answers designed to help you prepare for your next tech interview. Whether you're a beginner or an experienced developer, you'll find valuable insights and resources to sharpen your JavaScript skills and boost your confidence.
- Detailed Q&A: In-depth questions and answers covering all aspects of JavaScript.
- Concept Explanations: Clear explanations of fundamental and advanced JavaScript concepts.
- Code Examples: Practical examples to help you understand and apply JavaScript concepts.
- Interview Tips: Best practices and tips for acing your JavaScript interviews.
- Browse through the questions and answers to study and understand key JavaScript topics.
- Use the code examples to practice and solidify your knowledge.
- Follow the interview tips to improve your interview performance.
We welcome contributions! If you have any JavaScript interview questions or answers that you'd like to share, please feel free to open an issue or submit a pull request.
Happy coding and good luck with your interviews!
No. | Title | Show Answer |
---|---|---|
1 | What is JavaScript? | |
2 | Where can I use JavaScript? | |
3 | Which libraries and frameworks are built in JavaScript? | |
4 | What are primitive and non-primitive data types in JavaScript? | |
5 | Understanding References in JavaScript | |
6 | Including JavaScript Code in an HTML Document | |
7 | What is the difference between let , var , and const ? |
|
8 | How do you create a function in JavaScript? | |
9 | What is a JavaScript object, and how do you create one? | |
10 | What are arrays in JavaScript, and how do you use them? | |
11 | How do you write comments in JavaScript? | |
12 | What is the purpose of the this keyword in JavaScript? |
|
13 | What is the purpose of the this keyword in JavaScript? |
|
14 | What are JavaScript closures? | |
15 | What are JavaScript promises? | |
16 | What are the different types of loops in JavaScript? | |
17 | How do you perform string concatenation in JavaScript? | |
18 | What is the use of the typeof operator in JavaScript? |
|
19 | How do you create a multiline string in JavaScript? | |
20 | What are JavaScript events, and how are they used? | |
21 | How do you convert a string to a number in JavaScript? | |
22 | What is the difference between null and undefined ? |
|
23 | How do you use template literals in JavaScript? | |
24 | What are JavaScript operators, and what types exist? | |
25 | How do you write a conditional statement in JavaScript? | |
26 | What is the difference between alert , prompt , and confirm in JavaScript? |
|
27 | How do you perform arithmetic operations in JavaScript? | |
28 | How do you access and modify HTML elements using JavaScript? | |
29 | What are primitive and reference types in JavaScript? | |
30 | How do you use the instanceof operator in JavaScript? |
|
31 | What are default values for function parameters in JavaScript? | |
32 | How do you format a date in JavaScript? | |
33 | What is the eval function in JavaScript, and why is it considered dangerous? |
|
34 | How do you create a regular expression in JavaScript? | |
35 | How do you use the parseInt and parseFloat functions in JavaScript? |
|
36 | How do you use the Date object to get the current date and time? |
|
37 | What is the purpose of the with statement in JavaScript, and why is it discouraged? |
|
38 | How do you check if a variable is an array in JavaScript? | |
39 | What are the different ways to create an array in JavaScript? | |
40 | How do you add and remove items from an array in JavaScript? | |
41 | How do you change the content of an HTML element using JavaScript? | |
42 | What is type coercion in JavaScript? | |
# | Intermediate JavaScript Questions | Answer |
43 | What is the this keyword, and how is its context determined? |
|
44 | How do you clone an object in JavaScript? | |
45 | What are the different ways to iterate over an array in JavaScript? | |
46 | How do you create and handle custom events in JavaScript? | |
47 | What are arrow functions, and how do they differ from regular functions? | |
48 | How do you debounce and throttle functions in JavaScript? | |
49 | What is the purpose of the Object.freeze method? |
|
50 | How do you merge two or more objects in JavaScript? | |
51 | What is the difference between method and function in JavaScript? | |
52 | How do you use the Array.prototype.reduce method? |
|
53 | What is a higher-order function in JavaScript? | |
54 | How do you create a private variable in JavaScript? | |
55 | What is debouncing and throttling in JavaScript? | |
56 | How do you use the fetch API to make HTTP requests? |
|
57 | What are generator functions in JavaScript, and how do they work? | |
58 | How do you create a custom iterator in JavaScript? | |
59 | How do you create a deep copy of an object in JavaScript? | |
60 | What are rest parameters, and how are they used in JavaScript? | |
61 | How do you implement method chaining in JavaScript? | |
62 | How do you remove duplicates from an array in JavaScript? | |
63 | What is the difference between for...of and for...in loops in JavaScript? |
|
64 | How do you handle cross-origin requests in JavaScript? | |
65 | How do you use the Proxy object in JavaScript? |
|
66 | What is the Reflect object, and how is it used in JavaScript? |
|
67 | How do you debounce a function in JavaScript? | |
68 | What is the window object in JavaScript, and what are its properties and methods? |
|
# | Advanced JavaScript Questions | Answer |
- | ------------------------------------------------------------------------ | ---------------------------------------- |
69 | How do you use Proxy and Reflect in JavaScript? | |
70 | What is the concept of "hoisting" in JavaScript? | |
71 | What is a service worker in JavaScript? | |
72 | How do you implement a web worker in JavaScript? | |
73 | What are the benefits of using WebAssembly with JavaScript? | |
74 | How do you create a singleton pattern in JavaScript? | |
75 | What is memoization in JavaScript, and how do you implement it? | |
76 | How do you perform deep cloning of objects in JavaScript? | |
77 | What are the different ways to optimize memory usage in JavaScript? | |
78 | How do you manage state in a JavaScript application? | |
79 | What is the difference between mutable and immutable objects in JavaScript? | |
80 | How do you use the Reflect API in JavaScript? | |
81 | What is the module pattern in JavaScript? | |
82 | How do you implement inheritance using ES6 classes? | |
83 | What is a WeakMap in JavaScript, and how does it differ from a Map? | |
84 | How do you handle circular references in JavaScript objects? | |
85 | What is a microtask, and how does it differ from a macrotask in JavaScript? | |
86 | How do you implement a binary search algorithm in JavaScript? | |
87 | What are the benefits of using immutable data structures in JavaScript? | |
88 | How do you implement lazy loading in JavaScript? | |
89 | What are tagged templates in JavaScript? | |
90 | How do you implement a debounce function in JavaScript? | |
91 | How do you implement a simple pub/sub (publish-subscribe) system in JavaScript? | |
92 | What is tail call optimization in JavaScript? | |
93 | How do you create a memoization function in JavaScript? | |
94 | What is the Blob object in JavaScript, and how is it used? |
|
95 | How do you work with binary data in JavaScript? | |
96 | What is the File API in JavaScript, and how do you use it? |
|
97 | How do you handle large datasets efficiently in JavaScript? | |
98 | How do you create and manage WebSockets in JavaScript? | |
99 | What are the differences between localStorage, sessionStorage, and cookies in JavaScript? | |
100 | How do you implement a state machine in JavaScript? | |
101 | What is the DOM, and how is it structured? | |
102 | How do you select an element by its ID using JavaScript? | |
103 | How do you select elements by their class name using JavaScript? | |
104 | How do you select elements by their tag name using JavaScript? | |
105 | How do you create a new element and add it to the DOM? | |
106 | How do you remove an element from the DOM? | |
107 | How do you add an event listener to an element in the DOM? | |
108 | What is the difference between innerHTML and textContent? | |
109 | How do you change the style of an element using JavaScript? | |
110 | How do you use the Array.prototype.filter method? | |
111 | How do you use the Array.prototype.map method? | |
112 | What is the purpose of the Array.prototype.some method? | |
113 | How do you find the index of an element in an array using JavaScript? | |
114 | How do you merge two arrays in JavaScript? | |
115 | How do you convert an array to a string in JavaScript? | |
116 | What is the Array.prototype.every method used for? | |
117 | How do you find the first occurrence of a value in an array? | |
118 | How do you sort an array of objects by a property? | |
119 | How do you use the Array.prototype.slice method? | |
120 | How do you find the length of a string in JavaScript? | |
121 | How do you convert a string to uppercase in JavaScript? | |
122 | How do you check if a string contains a specific substring? | |
123 | How do you split a string into an array of substrings? | |
124 | How do you replace a part of a string with another string? | |
125 | How do you extract a substring from a string? | |
126 | How do you trim whitespace from the beginning and end of a string? | |
127 | How do you concatenate two strings in JavaScript? | |
128 | How do you repeat a string a specified number of times? | |
129 | How do you use template literals for string interpolation? | |
130 | What is the BOM, and what objects does it include? | |
131 | How do you get the width and height of the browser window? | |
132 | How do you open a new browser window using JavaScript? | |
133 | How do you navigate to a new URL using JavaScript? | |
134 | How do you get the current URL of the browser window? | |
135 | How do you interact with the browser history using JavaScript? | |
136 | How do you set a timeout to execute a function after a delay? | |
137 | How do you repeatedly execute a function at specified intervals? | |
138 | How do you detect the user's browser and version using JavaScript? | |
139 | How do you use the navigator object to get information about the user's environment? | |
140 | How do you get and set an element's attributes using JavaScript? | |
141 | How do you find all elements that match a specific CSS selector? | |
142 | How do you clone a DOM element and its children? | |
143 | How do you listen for changes to a form input field? | |
144 | How do you get the value of a selected option in a dropdown? | |
145 | How do you add a class to an element using JavaScript? | |
146 | How do you remove a class from an element using JavaScript? | |
147 | How do you toggle a class on an element using JavaScript? | |
148 | How do you prevent the default action of an event? | |
149 | How do you stop event propagation? | |
150 | How do you use the Array.prototype.reduceRight method? | |
151 | What is the Array.prototype.flat method, and how is it used? | |
152 | How do you use the Array.prototype.flatMap method? | |
153 | How do you use the Array.prototype.fill method to modify an array? | |
154 | What is the Array.prototype.copyWithin method used for? | |
155 | How do you create an array from an iterable or array-like object? | |
156 | How do you use the Array.from method with a map function? | |
157 | How do you use the Array.prototype.reverse method? | |
158 | What is the Array.prototype.keys method, and how is it used? | |
159 | How do you find the last index of an element in an array? | |
160 | How do you use the String.prototype.startsWith method? | |
161 | How do you use the String.prototype.endsWith method? | |
162 | What is the String.prototype.includes method used for? | |
163 | How do you use the String.prototype.charAt method? | |
164 | How do you get the character code of a character in a string? | |
165 | How do you convert a character code to a character? | |
166 | What is the String.prototype.codePointAt method, and how is it used? | |
167 | How do you normalize a string in JavaScript? | |
168 | How do you pad a string to a certain length? | |
169 | How do you match a string against a regular expression? | |
170 | How do you use the location object to reload the current page? | |
171 | How do you use the window object to move or resize the browser window? | |
172 | How do you detect if cookies are enabled in the user's browser? | |
173 | How do you get the user's screen dimensions using JavaScript? | |
174 | How do you use the history.pushState method to modify the browser history? | |
175 | How do you listen for changes in the browser history state? | |
176 | How do you detect when the user goes online or offline? | |
177 | How do you use the setTimeout function to delay the execution of code? | |
178 | How do you clear a timeout or interval that you have set? | |
179 | How do you use the alert, prompt, and confirm methods for user interaction? | |
180 | What are async functions and how do you use them? | |
181 | How do you use the async/await syntax in JavaScript? | |
182 | What is the purpose of the try...catch statement in JavaScript? | |
183 | How do you handle errors in asynchronous code in JavaScript? | |
184 | What is callback hell, and how do you avoid it? | |
185 | How do you use named exports in JavaScript modules? | |
186 | How do you use default exports in JavaScript modules? | |
187 | What are JavaScript modules, and how do you use them? | |
188 | How do you import and export modules in JavaScript? | |
189 | How do you implement inheritance in JavaScript using classes? | |
190 | What are JavaScript decorators, and how do you use them? | |
191 | What are generators in JavaScript, and how do they work? | |
192 | How do you create iterators in JavaScript? | |
193 | How do you use symbols in JavaScript? | |
194 | What are Sets and how do you use them in JavaScript? | |
195 | How do you use Promises in JavaScript? | |
196 | How do you use async/await in JavaScript? | |
197 | What is Event Delegation in JavaScript? | |
198 | How do you handle Cross-Site Scripting (XSS) in JavaScript? | |
199 | What is the JavaScript Event Loop? | |
200 | How do you implement a callback function in JavaScript? | |
201 | How do you handle symbol type in JavaScript? (ES6) | |
202 | How do you use iterators and generators in JavaScript? (ES6) | |
203 | How do you handle async iterators in JavaScript? (ES2018) | |
204 | How do you handle big integer operations? (ES2020) | |
205 | How do you use decorators in JavaScript? (Proposed) | |
206 | How do you handle the optional catch binding proposal? (ES2019) | |
207 | How do you use the globalThis proposal in JavaScript? (ES2020) | |
208 | How do you use the nullish coalescing operator? (ES2020) | |
209 | How do you use the optional chaining operator? (ES2020) | |
210 | How do you handle error causes in JavaScript? (Proposed ES2023) | |
211 | How do you use the class static block? (ES2022) | |
212 | How do you handle top-level await in JavaScript? (ES2022) | |
213 | How do you handle weak references in JavaScript? (ES2021) | |
214 | How do you handle numeric separators in JavaScript? (ES2021) | |
215 | How do you use the logical assignment operators? (ES2021) | |
216 | How do you use Promise.allSettled method? (ES2020) | |
217 | How do you implement functional programming concepts in JavaScript? | |
218 | How do you use the pipeline operator proposal in JavaScript? (Proposed) | |
219 | How do you use the throw expressions proposal in JavaScript? (Proposed) | |
220 | How do you handle the record and tuple proposal? (Proposed ES2024) | |
221 | How do you use the pattern matching proposal in JavaScript? (Proposed ES2024) | |
222 | How do you implement the temporal API in JavaScript? (Proposed ES2024) | |
223 | What are module attributes in JavaScript? (Proposed ES2024) | |
224 | How do you implement a task scheduler in JavaScript? | |
225 | How do you create a debounce function in JavaScript? | |
226 | How do you create a throttle function in JavaScript? | |
227 | How do you use setTimeout and setInterval in JavaScript? | |
228 | How do you handle asynchronous iterations in JavaScript? | |
229 | How do you use weak references and finalization registry? (ES2021) | |
230 | How do you implement a priority queue in JavaScript? | |
231 | How do you handle logical assignment operators? (ES2021) | |
232 | How do you handle the numeric separators proposal? (ES2021) | |
233 | How do you use iterators and generators? (ES6) | |
234 | How do you implement a graph data structure in JavaScript? | |
235 | How do you implement a binary search tree in JavaScript? | |
236 | How do you implement a linked list in JavaScript? | |
237 | How do you handle concurrency in JavaScript using web workers? | |
238 | How do you use the Atomics and SharedArrayBuffer objects in JavaScript? | |
239 | What are the new features in ES2024? | |
240 | How do you use the pattern matching proposal in JavaScript? (Proposed ES2024) | |
241 | How do you use record and tuple types in JavaScript? (Proposed ES2024) | |
242 | How do you implement the temporal API in JavaScript? (Proposed ES2024) | |
243 | What are module attributes in JavaScript? (Proposed ES2024) |
JavaScript is a versatile, high-level programming language primarily used for adding interactivity to web pages. It operates as an interpreted language, executing code line by line without prior compilation.
JavaScript was created by Brendan Eich in 1995 while he was at Netscape Communications Corporation. Originally named "Mocha" and later "LiveScript," it was rebranded as JavaScript to align with the popularity of Java.
-
Dynamic Typing: Variables can hold values of any data type without explicit declarations.
-
Prototype-based Object Orientation: Objects inherit properties and behaviors from prototypes.
-
Functional Programming Support: Functions are treated as first-class citizens, enabling higher-order functions and closures.
JavaScript can be used for both client-side and server-side development. It's integral to creating interactive web pages, developing web and mobile applications, building APIs, and even for server-side programming using platforms like Node.js.
JavaScript has a rich ecosystem of libraries and frameworks that simplify and enhance development. Some popular examples include:
-
React.js: A JavaScript library for building user interfaces.
-
AngularJS and Angular: Frameworks for building web applications.
-
Node.js: A runtime environment that allows JavaScript to run server-side.
These tools and frameworks extend JavaScript's capabilities beyond basic scripting, enabling robust application development across various platforms.
JavaScript supports different data types, categorized into primitive and non-primitive types.
- Primitive data: Primitive data types in JavaScript are immutable (unchangeable) and are directly operated upon by the language. They are stored directly in the variable's memory and are accessed by value.
Data Type | Description | Example |
---|---|---|
number |
Represents numeric data. | let count = 10; |
string |
Represents textual data. | let message = 'Hello'; |
boolean |
Represents logical values. | let isValid = true; |
null |
Represents intentional absence of any object value. | let data = null; |
undefined |
Represents a variable declared but not assigned a value. | let status; |
symbol |
Represents a unique identifier. | const id = Symbol('unique'); |
- Non-primitive: Non-primitive data types are mutable (changeable) and are not stored directly in the variable's allocated memory. Instead, they are stored as references, and accessing these variables points to the reference in memory.
Data Type | Description | Example |
---|---|---|
object |
Represents a collection of key-value pairs. | let person = { name: 'John', age: 30 }; |
array |
Represents a list-like collection of elements. | let numbers = [1, 2, 3, 4, 5]; |
function |
Represents a reusable block of code. | function greet(name) { return 'Hello, ' + name; } |
In JavaScript, references play a crucial role in how non-primitive data types are managed in memory. Unlike primitive data types (like numbers and strings) that are stored directly in the variable's location, non-primitive types (such as objects, arrays, and functions) are stored as references.
When you create a non-primitive data type, what actually gets stored in the variable is a reference to the memory location where the data is stored, rather than the data itself. This means:
-
Reference to Memory: Variables holding non-primitive types don't contain the actual data values but rather pointers or references to where the data resides in memory.
-
Passing by Reference: When you assign a non-primitive variable to another variable or pass it as an argument to a function, you're passing around this reference. This allows multiple variables to point to the same underlying data structure.
-
Mutability: Non-primitive types are mutable because you can change their properties or elements through their references. Modifying an object's property or adding/removing elements from an array affects the referenced data directly.
-
Memory Efficiency: References enable efficient memory usage because you're not duplicating large data structures every time you assign or pass them.
-
Flexibility: Referencing allows for complex data structures and dynamic changes without heavy memory overhead. This flexibility is crucial in modern JavaScript applications, where objects and arrays are commonly used to represent complex data relationships.
// Example of referencing in JavaScript
// Object creation let person1 = { name: 'John', age: 30 };
// person2 references the same object as person1 let person2 = person1;
// Modifying person2 affects the referenced object person2.age = 35;
console.log(person1.age); // Output: 35 (because person1 and person2 point to the same object)
To include JavaScript code in an HTML document, you can use the <script> tag. Here's how it works:
Use the <script>
tag within the <head>
or <body>
section of your HTML document.
You can write JavaScript code directly within <script>
tags in your HTML file:
Alternatively, you can link to an external JavaScript file using the src attribute of the <script> tag.
<script src="path/to/your/script.js"></script>In JavaScript, let, var, and const are used to declare variables, but they behave differently in terms of scoping, hoisting, and mutability. Understanding their differences is crucial for writing clean and maintainable code.
In JavaScript, variables can be declared using var
. Understanding how var
behaves in terms of scoping, hoisting, and mutability is important for writing robust and maintainable code.
- Scope:
var
variables are function-scoped or globally-scoped. They are not block-scoped, which means they are visible throughout the entire function or global context. - Hoisting: Variables declared with
var
are hoisted to the top of their function or global scope. This means you can use the variable before it's declared in the code. - Reassignable:
var
variables can be redeclared and reassigned within their scope.
function example() { var x = 10; if (true) { var x = 20; console.log(x); // Outputs: 20 } console.log(x); // Outputs: 20 }
In JavaScript, let
is used to declare variables that are block-scoped. This means they are limited to the block ({ }
) in which they are defined, such as if
, for
, or while
blocks.
- Scope:
let
variables are block-scoped, meaning they are limited to the block ({ }
) in which they are defined, such asif
,for
, orwhile
blocks. - Hoisting: Variables declared with
let
are hoisted to the top of their block, but unlikevar
, they are not initialized until their declaration is evaluated. Accessing alet
variable before its declaration results in aReferenceError
. - Reassignable:
let
variables can be reassigned but cannot be redeclared in the same scope.
function example() { let x = 10; // Declaring 'x' using let if (true) { let x = 20; // 'x' redeclared within the block console.log(x); // Outputs: 20 } console.log(x); // Outputs: 10 (outside the block) } example();
In JavaScript, const
is used to declare variables that are block-scoped and must be initialized with a value that cannot be reassigned.
- Scope:
const
variables are block-scoped, meaning they are limited to the block ({ }
) in which they are defined, such asif
,for
, orwhile
blocks. - Hoisting: Variables declared with
const
are hoisted to the top of their block, but they are not initialized until their declaration is evaluated. - Immutability:
const
variables must be initialized with a value when declared, and once initialized, their value cannot be reassigned. However, for objects and arrays, properties can be mutated.
function example() { const x = 10; // Declaring 'x' using const // x = 20; // Error: Assignment to constant variable 'x' is not allowed const y = { name: 'John' }; // Declaring 'y' as a const object y.name = 'Jane'; // Valid: Changing property of a const object console.log(y); // Outputs: { name: 'Jane' } } example();
When working with variables in JavaScript, choosing between let
, var
, and const
depends on their intended usage and requirements:
-
Use
const
by default: Useconst
for variables that will not be reassigned. This promotes immutability and helps prevent accidental reassignments. -
Use
let
for variables that need to be reassigned: When you anticipate that a variable's value will change during the program's execution, opt forlet
. This approach provides clarity and avoids confusion about the variable's mutability. -
Avoid
var
unless necessary:var
has broader scope rules and can lead to unexpected behaviors due to hoisting and lack of block scoping. However, in some legacy code or specific scenarios where you need function-scoped variables,var
may still be used.
Understanding the differences between let
, var
, and const
will enable you to choose the appropriate variable declaration based on your specific programming needs and best practices.
Move to Top
Functions in JavaScript are essential for organizing and reusing code. There are several methods to create functions, each suited for different scenarios and coding styles.
Function declarations are defined using the function
keyword, followed by the function name, parameters (optional), and a function body enclosed in curly braces {}
.
// Function declaration function greet(name) { return `Hello, ${name}!`; } // Calling the function console.log(greet("Alice")); // Outputs: Hello, Alice!
Function expressions define functions using the function keyword without specifying a function name (anonymous function). These can be assigned to variables or passed as arguments to other functions.
// Function expression (anonymous function) const greet = function(name) { return `Hello, ${name}!`; }; // Calling the function console.log(greet("Bob")); // Outputs: Hello, Bob!
Arrow functions provide a concise syntax introduced in ES6. They use the => syntax and automatically bind this to the surrounding context.
// Arrow function const greet = (name) => { return `Hello, ${name}!`; }; // Calling the function console.log(greet("Eve")); // Outputs: Hello, Eve!
In JavaScript, functions can also be defined as methods within objects or classes. These functions are associated with specific objects and are invoked using dot notation (object.method())
// Method function const person = { name: "John", greet: function() { return `Hello, ${this.name}!`; } }; // Calling the method function console.log(person.greet()); // Outputs: Hello, John!
In JavaScript, an object is a fundamental data structure consisting of key-value pairs. It allows you to store and access data through named properties. Objects are versatile and can represent complex data structures.
There are several ways to create objects in JavaScript:
let person = { firstName: 'John', lastName: 'Doe', age: 30, hobbies: ['reading', 'music', 'sports'], address: { street: '123 Main St', city: 'Anytown', state: 'CA' }, fullName: function() { return this.firstName + ' ' + this.lastName; } };
let person = new Object(); person.firstName = 'John'; person.lastName = 'Doe'; person.age = 30; person.hobbies = ['reading', 'music', 'sports']; person.address = { street: '123 Main St', city: 'Anytown', state: 'CA' }; person.fullName = function() { return this.firstName + ' ' + this.lastName; };
let personPrototype = { fullName: function() { return this.firstName + ' ' + this.lastName; } }; let person = Object.create(personPrototype); person.firstName = 'John'; person.lastName = 'Doe'; person.age = 30; person.hobbies = ['reading', 'music', 'sports']; person.address = { street: '123 Main St', city: 'Anytown', state: 'CA' };
class Person { constructor(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } fullName() { return `${this.firstName} ${this.lastName}`; } } let person = new Person('John', 'Doe', 30);
You can access properties of an object using dot notation (.) or bracket notation ([]):
console.log(person.firstName); // Outputs: John console.log(person['lastName']); // Outputs: Doe
You can modify properties of an object after its creation:
person.age = 32; person['hobbies'].push('painting');
Objects can contain functions as values. These functions are called methods:
let person = { firstName: 'John', lastName: 'Doe', fullName: function() { return this.firstName + ' ' + this.lastName; } }; console.log(person.fullName()); // Outputs: John Doe
In JavaScript, an array is a special type of object used to store multiple values in a single variable. Arrays allow you to group values of any data type (including other arrays) sequentially under a single identifier. They are versatile and commonly used for storing lists of items or collections of related data.
There are several ways to create arrays in JavaScript:
let fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
let fruits = new Array('Apple', 'Banana', 'Cherry', 'Date');
However, using array literal syntax ([]) is generally preferred due to its simplicity and readability.
- Accessing Array Elements: You can access elements in an array using square brackets ([]) and the index of the element (0-based index):
let fruits = ['Apple', 'Banana', 'Cherry', 'Date']; console.log(fruits[0]); // Outputs: Apple console.log(fruits[2]); // Outputs: Cherry
- Modifying Array Elements: You can modify elements in an array directly by assigning a new value to a specific index:
let fruits = ['Apple', 'Banana', 'Cherry', 'Date']; fruits[1] = 'Orange'; console.log(fruits); // Outputs: ['Apple', 'Orange', 'Cherry', 'Date']
- Array Properties and Methods Arrays in JavaScript have various properties and methods that allow you to manipulate them effectively:
- Length Property : Returns the number of elements in the array.
console.log(fruits.length); // Outputs: 4
- Push Method : Adds one or more elements to the end of an array and returns the new length of the array.
fruits.push('Fig'); console.log(fruits); // Outputs: ['Apple', 'Orange', 'Cherry', 'Date', 'Fig']
In JavaScript, comments are used to annotate code and provide explanations or notes that are ignored by the JavaScript engine during execution. They are helpful for documenting code, explaining functionality, and making it easier for other developers (or your future self) to understand.
JavaScript supports two main types of comments:
Single-line comments start with // and continue until the end of the line. They are used for brief comments on a single line of code.
// This is a single-line comment let greeting = 'Hello'; // This comment explains the variable purpose
Multi-line comments start with /* and end with */. They can span across multiple lines and are typically used for longer explanations or commenting out multiple lines of code.
/* * This is a multi-line comment. * It can span across several lines. * These comments are often used for detailed explanations or notes. */ let message = 'Welcome'; /* This comment is inline with code */