JavaScript Basics

Understand JavaScript fundamentals, including variables, data types, operators, conditions, loops, functions, arrays, objects, scope, modern syntax, error handling, and asynchronous programming.

Lesson content

What is JavaScript? JavaScript is a programming language used to add logic, interactivity, data processing, and dynamic behavior to web applications. Angular applications are commonly written in TypeScript, which builds on JavaScript by adding static types and development tooling. Simple Formula HTML = Page Structure CSS = Page Styling JavaScript = Logic and Behavior 1. Display Output Console Output console.log( 'Hello, JavaScript' ); Warning console.warn( 'This is a warning' ); Error console.error( 'Something went wrong' ); 2. Comments Single-Line Comment // This is a comment. const name = 'Ajay'; Multi-Line Comment /* This comment uses multiple lines. */ 3. Variables Variables store values that can be used later. const const country = 'India'; Use const when the variable should not be reassigned. let let score = 10; score = 20; Use let when the variable must be reassigned. var var oldValue = 10; Avoid var in modern JavaScript because its function scope and hoisting behavior can create unexpected results. Recommended Rule Use const by default. Use let when reassignment is required. Avoid var. 4. Variable Naming Rules Valid Names const userName = 'Ajay'; const user1 = 'Rahul'; const _status = 'active'; const $price = 100; Invalid Names const 1user = 'Ajay'; const user-name = 'Ajay'; const const = 'value'; Best Practice Use camelCase: firstName totalAmount isLoggedIn 5. Primitive Data Types Type Example String 'Ajay' Number 100 Boolean true Undefined undefined Null null BigInt 123n Symbol Symbol('id') 6. String const firstName = 'Ajay'; const lastName = "Rajpoot"; Template Literal const fullName = `${firstName} ${lastName}`; Multi-Line String const message = ` Welcome to JavaScript learning. `; 7. Number const age = 30; const price = 199.99; const negativeValue = -10; Basic Calculation const total = 100 + 50; console.log(total); 8. Boolean const isActive = true; const isDeleted = false; Booleans are commonly used in conditions and application state. 9. Undefined and Null Undefined let userName; console.log( userName ); Undefined usually means that a value has not been assigned. Null let selectedUser = null; Null is commonly used to represent an intentionally empty value. 10. Check a Data Type console.log( typeof 'Ajay' ); console.log( typeof 100 ); console.log( typeof true ); Output string number boolean 11. Reference Data Types Objects, arrays, and functions are reference values. Object const user = { id: 1, name: 'Ajay' }; Array const numbers = [ 10, 20, 30 ]; Function function greet() { console.log( 'Hello' ); } 12. Arithmetic Operators Operator Purpose + Addition - Subtraction * Multiplication / Division % Remainder ** Exponent Example const a = 10; const b = 3; console.log(a + b); console.log(a - b); console.log(a * b); console.log(a / b); console.log(a % b); console.log(a ** b); 13. Assignment Operators let value = 10; value += 5; value -= 2; value *= 3; value /= 2; Meaning value += 5 is equivalent to: value = value + 5 14. Comparison Operators Operator Meaning === Strict equality !== Strict inequality > Greater than < Less than >= Greater than or equal <= Less than or equal Example console.log( 10 === 10 ); console.log( 10 !== 5 ); console.log( 10 > 5 ); 15. Strict vs Loose Equality Loose Equality console.log( 5 == '5' ); Strict Equality console.log( 5 === '5' ); Result 5 == '5' → true 5 === '5' → false Prefer strict equality because it compares both value and type. 16. Logical Operators Operator Meaning && Logical AND || Logical OR ! Logical NOT AND const canAccess = isLoggedIn && isActive; OR const canEdit = isAdmin || isManager; NOT const isGuest = !isLoggedIn; 17. if Statement const age = 20; if (age >= 18) { console.log( 'Adult' ); } 18. if...else const age = 16; if (age >= 18) { console.log( 'Adult' ); } else { console.log( 'Minor' ); } 19. else if const marks = 75; if (marks >= 90) { console.log('Grade A'); } else if ( marks >= 70 ) { console.log('Grade B'); } else if ( marks >= 50 ) { console.log('Grade C'); } else { console.log('Failed'); } 20. Ternary Operator const age = 20; const result = age >= 18 ? 'Adult' : 'Minor'; Formula condition ? valueWhenTrue : valueWhenFalse 21. switch Statement const role = 'admin'; switch (role) { case 'admin': console.log( 'Admin dashboard' ); break; case 'manager': console.log( 'Manager dashboard' ); break; default: console.log( 'User dashboard' ); } 22. Truthy and Falsy Values Common Falsy Values false 0 '' null undefined NaN Truthy Example const name = 'Ajay'; if (name) { console.log( 'Name exists' ); } 23. Nullish Coalescing The nullish coalescing operator provides a fallback only for null or undefined . const userName = receivedName ?? 'Guest'; Difference from OR const value = 0; console.log( value || 10 ); console.log( value ?? 10 ); Output 10 0 24. Optional Chaining Optional chaining safely reads nested values that may be missing. const city = user.address?.city; Without Optional Chaining const city = user.address ? user.address.city : undefined; 25. for Loop for ( let index = 0; index < 5; index++ ) { console.log(index); } Output 0 1 2 3 4 26. while Loop let count = 0; while (count < 3) { console.log(count); count++; } 27. do...while Loop let count = 0; do { console.log(count); count++; } while ( count < 3 ); A do...while loop executes at least once. 28. for...of Use for...of to iterate over array values. const users = [ 'Ajay', 'Rahul', 'Sneha' ]; for ( const user of users ) { console.log(user); } 29. for...in Use for...in to iterate over enumerable object keys. const user = { id: 1, name: 'Ajay' }; for ( const key in user ) { console.log( key, user[key] ); } Avoid using for...in for normal array value iteration. 30. break and continue break for ( let index = 0; index < 10; index++ ) { if (index === 5) { break; } console.log(index); } continue for ( let index = 0; index < 5; index++ ) { if (index === 2) { continue; } console.log(index); } 31. Functions A function groups reusable logic. Function Declaration function add( firstNumber, secondNumber ) { return ( firstNumber + secondNumber ); } const total = add(10, 20); 32. Function Parameters and Arguments function greet(name) { console.log( `Hello, ${name}` ); } greet('Ajay'); Meaning name = Parameter 'Ajay' = Argument 33. Default Parameters function greet( name = 'Guest' ) { return `Hello, ${name}`; } console.log( greet() ); 34. Function Expression const multiply = function ( firstNumber, secondNumber ) { return ( firstNumber * secondNumber ); }; 35. Arrow Function const add = ( firstNumber, secondNumber ) => { return ( firstNumber + secondNumber ); }; Short Arrow Function const add = (a, b) => a + b; 36. Return Value function calculateTotal( price, quantity ) { return ( price * quantity ); } const total = calculateTotal( 100, 3 ); Code after a return statement inside the same block does not execute. 37. Scope Scope determines where a variable can be accessed. Global Scope const applicationName = 'Learning App'; function showName() { console.log( applicationName ); } Function Scope function calculate() { const total = 100; console.log(total); } Block Scope if (true) { const message = 'Inside block'; let count = 1; } Variables declared with let and const are block-scoped. 38. Hoisting JavaScript processes declarations before executing code, but different declaration types behave differently. Function Declaration greet(); function greet() { console.log('Hello'); } let and const console.log(name); const name = 'Ajay'; Accessing a let or const variable before initialization causes an error. 39. Arrays const numbers = [ 10, 20, 30 ]; Read an Item console.log( numbers[0] ); Array Length console.log( numbers.length ); 40. Add and Remove Array Items push() numbers.push(40); pop() numbers.pop(); unshift() numbers.unshift(5); shift() numbers.shift(); Method Action push() Add to end pop() Remove from end unshift() Add to beginning shift() Remove from beginning 41. Array forEach() const users = [ 'Ajay', 'Rahul' ]; users.forEach( user => { console.log(user); } ); The forEach() method performs an action for each array item. 42. Array map() The map() method creates a new array by transforming every item. const numbers = [ 1, 2, 3 ]; const doubled = numbers.map( number => number * 2 ); Result [2, 4, 6] 43. Array filter() The filter() method creates a new array containing matching items. const numbers = [ 10, 20, 30, 40 ]; const largeNumbers = numbers.filter( number => number > 20 ); Result [30, 40] 44. Array find() The find() method returns the first matching item. const users = [ { id: 1, name: 'Ajay' }, { id: 2, name: 'Rahul' } ]; const user = users.find( item => item.id === 2 ); 45. Array some() and every() some() const hasAdult = users.some( user => user.age >= 18 ); every() const allActive = users.every( user => user.active ); Meaning some() = At Least One Matches every() = All Items Match 46. Array reduce() The reduce() method combines array items into one result. const prices = [ 100, 200, 300 ]; const total = prices.reduce( ( currentTotal, price ) => currentTotal + price, 0 ); Result 600 47. Objects const user = { id: 1, name: 'Ajay', active: true }; Dot Notation console.log( user.name ); Bracket Notation console.log( user['name'] ); 48. Update an Object user.name = 'Rahul'; user.active = false; Add a Property user.email = 'user@example.com'; Delete a Property delete user.active; 49. Object Methods const user = { name: 'Ajay', greet() { return ( `Hello, ${this.name}` ); } }; console.log( user.greet() ); 50. this Keyword The value of this depends on how a function is called. const user = { name: 'Ajay', showName() { console.log( this.name ); } }; user.showName(); Arrow functions do not create their own this value. 51. Object Destructuring const user = { id: 1, name: 'Ajay' }; const { id, name } = user; Rename a Property const { name: userName } = user; 52. Array Destructuring const numbers = [ 10, 20, 30 ]; const [ first, second ] = numbers; 53. Spread Operator Copy an Array const numbers = [ 1, 2, 3 ]; const copiedNumbers = [ ...numbers ]; Add Array Items const updatedNumbers = [ ...numbers, 4 ]; Copy an Object const updatedUser = { ...user, active: false }; 54. Rest Parameters function addAll( ...numbers ) { return numbers.reduce( ( total, number ) => total + number, 0 ); } addAll( 10, 20, 30 ); 55. Shallow Copy Spread syntax creates a shallow copy. const original = { name: 'Ajay', address: { city: 'Delhi' } }; const copied = { ...original }; copied.address.city = 'Gurugram'; The nested address object is still shared between both objects. 56. String Methods const text = ' JavaScript Basics '; Common Methods text.length text.toUpperCase() text.toLowerCase() text.trim() text.includes( 'Script' ) text.startsWith( 'Java' ) text.replace( 'Basics', 'Fundamentals' ) text.split(' ') 57. Number Conversion String to Number const value = Number('100'); Integer Parsing const value = parseInt( '100px', 10 ); Decimal Parsing const value = parseFloat( '10.50' ); Number to String const text = String(100); 58. NaN NaN means that a value is not a valid number. const result = Number( 'Hello' ); console.log( Number.isNaN(result) ); 59. Date const currentDate = new Date(); Specific Date const date = new Date( '2026-07-25' ); Read Date Values date.getFullYear(); date.getMonth(); date.getDate(); date.getDay(); The month returned by getMonth() starts at zero. 60. Set and Map Set A Set stores unique values. const numbers = new Set([ 1, 2, 2, 3 ]); console.log( [...numbers] ); Result [1, 2, 3] Map A Map stores key-value pairs and supports keys of different types. const userRoles = new Map(); userRoles.set( 1, 'admin' ); console.log( userRoles.get(1) ); 61. Error Handling try { const result = riskyOperation(); console.log(result); } catch (error) { console.error( 'Operation failed', error ); } finally try { loadData(); } catch (error) { console.error(error); } finally { console.log( 'Operation completed' ); } The finally block runs whether the operation succeeds or fails. 62. Throw an Error function withdraw( balance, amount ) { if (amount > balance) { throw new Error( 'Insufficient balance' ); } return ( balance - amount ); } 63. JSON JSON is a text format commonly used for API data. Object to JSON const json = JSON.stringify( user ); JSON to Object const userObject = JSON.parse(json); 64. Callback Function A callback is a function passed to another function. function processUser( name, callback ) { callback(name); } processUser( 'Ajay', userName => { console.log( `Hello, ${userName}` ); } ); 65. Promise A Promise represents the future success or failure of an asynchronous operation. const promise = new Promise( ( resolve, reject ) => { const success = true; if (success) { resolve( 'Data loaded' ); } else { reject( new Error( 'Loading failed' ) ); } } ); Consume a Promise promise .then(result => { console.log(result); }) .catch(error => { console.error(error); }) .finally(() => { console.log( 'Finished' ); }); 66. async and await async function loadUser() { try { const response = await fetch( '/api/users/1' ); if (!response.ok) { throw new Error( 'Request failed' ); } const user = await response.json(); console.log(user); } catch (error) { console.error(error); } } Async Flow Start Request ↓ await Response ↓ Parse JSON ↓ Use Result 67. Promise.all() Use Promise.all() when multiple independent asynchronous operations can run together. const [ users, products ] = await Promise.all([ fetchUsers(), fetchProducts() ]); Benefit Sequential: Request A → Wait → Request B Parallel: Request A and Request B Start Together 68. Classes class User { constructor( id, name ) { this.id = id; this.name = name; } greet() { return ( `Hello, ${this.name}` ); } } const user = new User( 1, 'Ajay' ); 69. Inheritance class Employee extends User { constructor( id, name, role ) { super( id, name ); this.role = role; } } 70. Modules Export export function add( firstNumber, secondNumber ) { return ( firstNumber + secondNumber ); } Import import { add } from './math.js'; console.log( add(10, 20) ); Default Export export default class UserService {} Default Import import UserService from './user-service.js'; 71. Primitive vs Reference Assignment Primitive Copy let firstValue = 10; let secondValue = firstValue; secondValue = 20; Changing the second primitive value does not change the first. Reference Copy const firstUser = { name: 'Ajay' }; const secondUser = firstUser; secondUser.name = 'Rahul'; Both variables refer to the same object. 72. Closures A closure allows a function to remember variables from its outer scope. function createCounter() { let count = 0; return function () { count++; return count; }; } const counter = createCounter(); console.log( counter() ); console.log( counter() ); Output 1 2 73. Basic DOM Interaction const button = document.querySelector( '#saveButton' ); button?.addEventListener( 'click', () => { console.log( 'Button clicked' ); } ); In Angular applications, prefer Angular templates, event binding, signals, and Renderer APIs instead of frequent direct DOM manipulation. 74. JavaScript and Angular Example import { Component, computed, signal } from '@angular/core'; @Component({ selector: 'app-counter', template: ` <p> Count: {{ count() }} </p> <p> Double: {{ doubleCount() }} </p> <button type="button" (click)="increment()" > Increment </button> ` }) export class CounterComponent { count = signal(0); doubleCount = computed( () => this.count() * 2 ); increment() { this.count.update( value => value + 1 ); } } Common Mistakes 1. Using var Prefer const and let because they provide block scope. 2. Using Loose Equality Avoid value == '10' Prefer value === 10 3. Forgetting return const add = (a, b) => { a + b; }; This function returns undefined . Correct const add = (a, b) => { return a + b; }; 4. Mutating Shared Objects Unexpectedly const updatedUser = { ...user, active: false }; 5. Using map() Without Returning a Value Incorrect numbers.map( number => { number * 2; } ); Correct numbers.map( number => number * 2 ); 6. Using for...in for Array Values Use for...of , forEach() , or array methods for normal array iteration. 7. Ignoring Promise Errors Use catch() or try...catch with awaited Promises. 8. Accessing Nested Properties Without Checking const city = user.address?.city; 9. Confusing null and undefined Undefined generally means missing or unassigned, while null usually represents an intentionally empty value. 10. Using Large Global Variables Keep variables in the smallest practical scope. Best Practices Use const by default Use let only when reassignment is required Avoid var Use strict equality Use meaningful variable and function names Keep functions small and focused Prefer array methods for collection transformations Avoid unexpected object mutation Use optional chaining for nullable nested values Use nullish coalescing for null and undefined fallbacks Handle asynchronous errors Use modules to organize code Keep variables in limited scope Use TypeScript for large Angular applications Interview Questions What is JavaScript? JavaScript is a programming language used to implement logic, interaction, data processing, and dynamic behavior in applications. What is the difference between let and const? A let variable can be reassigned, while a const variable cannot be reassigned. What is the difference between == and ===? Loose equality performs type conversion, while strict equality compares both value and type. What is a primitive value? A primitive is a simple value such as a string, number, boolean, null, undefined, BigInt, or Symbol. What is an array? An array is an ordered collection of values. What is an object? An object stores related values as key-value properties. What does map() do? It transforms every array item and returns a new array. What does filter() do? It returns a new array containing items that satisfy a condition. What does reduce() do? It combines array items into a single result. What is a function? A function is a reusable block of code that can accept parameters and return a value. What is scope? Scope defines where variables and functions can be accessed. What is a closure? A closure is a function that retains access to variables from its outer lexical scope. What is a Promise? A Promise represents the future completion or failure of an asynchronous operation. What is async/await? It is syntax for working with Promises in a style that resembles synchronous code. What is optional chaining? Optional chaining safely accesses a property or method when an earlier value may be null or undefined. What is the spread operator? Spread syntax expands array items or object properties into another array, object, or function call. Key Point JavaScript fundamentals provide the foundation for understanding TypeScript, Angular components, services, RxJS, events, forms, and application logic. Easy Formula JavaScript Basics = Variables + Data Types + Operators + Conditions + Loops + Functions + Arrays + Objects Array Transformation → map() Array Filtering → filter() Find One Item → find() Combine Values → reduce() Synchronous Logic → Normal Functions Asynchronous Logic → Promise + async + await