Javascript Basic Syntax And Code Execution Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of JavaScript Basic Syntax and Code Execution

JavaScript Basic Syntax and Code Execution: A Comprehensive Guide

Variables

Variables are used to store data in memory. JavaScript uses the let, const, and var keywords to declare variables.

  • let: This keyword allows you to declare block-scoped variables—variables that exist only within the block they are defined. This helps prevent errors and potential bugs by limiting variable scope.

    let x = 10;
    if (true) {
        let x = 20; // different variable
        console.log(x); // 20
    }
    console.log(x); // 10
    
  • const: Similar to let, but const is used for declaring constants, which means the value of the variable cannot be reassigned after being initially set. This ensures the integrity of values you intend to keep unchanged throughout your application.

    const pi = 3.14;
    pi = 3.15; // TypeError: Assignment to constant variable.
    
  • var: Unlike let and const, var is function-scoped. Variables declared using var can be accessed throughout the function they are declared in, ignoring block scopes.

    var y = 5;
    if (true) {
        var y = 25; // same variable
        console.log(y); // 25
    }
    console.log(y); // 25
    

    Note: It's generally recommended to avoid using var due to its function-scoping characteristic, especially in modern JavaScript environments.

Data Types

JavaScript supports various data types including primitive types and objects.

  • Primitive Types: These include:

    • Number: Represents both integer and floating-point values (e.g., 5, 3.14).
    • String: Represents textual data (e.g., "Hello, World!", 'JavaScript').
    • Boolean: Represents logical entity and can have only two values: true or false.
    • Null: Represents the intentional absence of any object or value (e.g., null).
    • Undefined: Represents a variable that has not been assigned a value or not declared at all (e.g., undefined).
    • Symbol: Introduced in ES6, represents a unique and immutable value (e.g., Symbol('description')).
    • BigInt: Allows representing very large whole numbers that are outside the safe integer range (e.g., 1234567890123456789012345678901234567890n).
  • Objects: JavaScript objects are key-value pairs where keys are strings and values can be any data type.

    const person = {
        name: "John",
        age: 30,
        isEmployed: true
    };
    console.log(person.name); // John
    

Operators

JavaScript includes a variety of operators to perform operations on data.

  • Arithmetic Operators: +, -, *, /, %, **, ++, --.

    let a = 10;
    let b = 5;
    console.log(a + b); // 15
    console.log(a / b); // 2
    console.log(a % b); // 0
    
  • Assignment Operators: =, +=, -=, *=, /=, %=, **=.

    let c = 10;
    c += 5; // equivalent to c = c + 5
    console.log(c); // 15
    
  • Comparison Operators: ==, !=, ===, !==, >, <, >=, <=.

    let d = 5;
    let e = '5';
    console.log(d == e);  // true (equality operator checks only value)
    console.log(d === e); // false (strict equality operator checks value and type)
    
  • Logical Operators: &&, ||, !.

    let f = true;
    let g = false;
    console.log(f && g); // false (AND)
    console.log(f || g); // true (OR)
    console.log(!f);     // false (NOT)
    

Control Structures

Control structures determine the flow of your program based on conditions or loops.

  • Conditional Statements: if, else if, else.

    let h = 20;
    if (h > 30) {
        console.log("Greater than 30");
    } else if (h === 20) {
        console.log("Equal to 20"); // This gets executed
    } else {
        console.log("Less than 20");
    }
    
  • Switch Statements: A better alternative to multiple if-else statements.

    let day = "Monday";
    switch (day) {
        case "Monday":
            console.log("Start of the work week!");
            break;
        case "Tuesday":
            console.log("Second day.");
            break;
        default:
            console.log("Another day...");
    }
    
  • Loops: Used to execute a block of statements repeatedly.

    • For Loop:

      for (let i = 0; i < 5; i++) {
          console.log(i);
      }
      
    • While Loop:

      let j = 0;
      while (j < 5) {
          console.log(j);
          j++;
      }
      
    • Do-While Loop: Ensures the loop body is executed at least once before checking the condition.

      let k = 0;
      do {
          console.log(k);
          k++;
      } while (k < 5);
      
  • For-In Loop: Iterates over the properties of an object.

    const obj = {a: 1, b: 2, c: 3};
    for (let prop in obj) {
        console.log(prop + ": " + obj[prop]);
        // a: 1
        // b: 2
        // c: 3
    }
    
  • For-Of Loop: Iterates over iterable objects such as arrays.

    const arr = [10, 20, 30];
    for (let val of arr) {
        console.log(val);
        // 10
        // 20
        // 30
    }
    

Functions

Functions are blocks of code designed to perform a particular task and can be reused. JavaScript function definitions start with the function keyword followed by the function name and parentheses.

function greet(name) {
    return "Hello, " + name + "!";
}

console.log(greet("Alice")); // Hello, Alice!

Arrow Functions: Introduced in ES6, provide a more concise syntax for writing functions (especially for short functions).

const add = (a, b) => a + b;
console.log(add(5, 6)); // 11

Function Expressions: A function that is assigned to a variable.

const sayHello = function(name) {
    return "Hi, " + name + "!";
};

console.log(sayHello("Bob")); // Hi, Bob!

Immediately Invoked Function Expressions (IIFE): Functions that run right after being defined.

(function() {
    console.log("This will run immediately!");
})();

Code Execution

Understanding how JavaScript executes code is crucial for efficient development. JavaScript is a single-threaded language but can handle asynchronous operations using mechanisms like the event loop.

  • Single-threading: JavaScript code runs in a single thread, meaning only one script can run at a time. However, the event loop allows asynchronous operations to be managed effectively.

  • Asynchronous Execution: Operations that take time (like HTTP requests or timers) do not block subsequent code execution. Instead, they use callbacks, promises, or async/await to manage asynchronous operations.

    // Using setTimeout to introduce asynchronous behavior
    console.log("Before setTimeout");
    
    setTimeout(() => {
        console.log("This runs after 2 seconds");
    }, 2000);
    
    console.log("After setTimeout");
    
    // Output:
    // Before setTimeout
    // After setTimeout
    // This runs after 2 seconds
    
  • Event Loop: The event loop is a system by which JavaScript handles asynchronous operations. It continuously checks if there's code in the call stack (the stack of functions currently being executed) and the task queue (tasks awaiting execution) to run.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement JavaScript Basic Syntax and Code Execution

Introduction to JavaScript

JavaScript is a programming language that's used mainly for website development to create interactive web pages. It's an essential technology of the World Wide Web, alongside HTML and CSS. JavaScript allows web developers to implement complex features on web pages, like dynamic content updates and interactive maps.

Basic Syntax and Code Execution

1. Comments

Comments are used to explain your code. They are not executed by the computer. In JavaScript, there are two types of comments:

  • Single-line comments: start with //.
  • Multi-line comments: start with /* and end with */.

Example:

// This is a single-line comment

/*
This is a multi-line comment
on multiple lines
*/

2. Variables

Variables are like containers for storing data. In JavaScript, you can use let, const, or var to declare variables.

Example:

let name = "Alice"; // Declaring a variable using let
const age = 25;     // Declaring a constant using const
var city = "New York"; // Declaring a variable using var (avoid using var in modern JavaScript)

console.log(name); // Output: Alice
console.log(age);  // Output: 25
console.log(city); // Output: New York

3. Data Types

JavaScript supports multiple data types:

  • Primitive types: number, string, boolean, undefined, null, symbol.
  • Composite types: object, array (arrays are objects).

Example:

let number = 42; // Number
let text = "Hello, World!"; // String
let isTrue = true; // Boolean
let nothing = undefined; // Undefined
let empty = null; // Null
let symbolValue = Symbol('description'); // Symbol

let person = { // Object
    name: "Bob",
    age: 30
};

let fruits = ["Apple", "Banana", "Cherry"]; // Array

console.log(typeof number); // Output: number
console.log(typeof text); // Output: string
console.log(typeof isTrue); // Output: boolean
console.log(typeof nothing); // Output: undefined
console.log(typeof empty); // Output: object
console.log(typeof symbolValue); // Output: symbol
console.log(typeof person); // Output: object
console.log(typeof fruits); // Output: object

4. Operators

Operators perform actions on variables and values. Common types of operators include:

  • Arithmetic operators: +, -, *, /, % (modulus), ** (exponentiation).
  • Assignment operators: =, +=, -=, *=, /=, etc.
  • Comparison operators: ==, ===, !=, !==, >, <, >=, <=.
  • Logical operators: && (and), || (or), ! (not).

Example:

let x = 10, y = 5;

console.log(x + y); // Output: 15 (Addition)
console.log(x - y); // Output: 5 (Subtraction)
console.log(x * y); // Output: 50 (Multiplication)
console.log(x / y); // Output: 2 (Division)
console.log(x % y); // Output: 0 (Modulus)
console.log(x ** y); // Output: 100000 (Exponentiation)

x += 5; // Equivalent to x = x + 5
console.log(x); // Output: 15

console.log(x == 15); // Output: true (Equality)
console.log(y >= 5); // Output: true (Greater than or equal to)
console.log(x > y && y < x); // Output: true (Logical AND)
console.log(x > y || y > x); // Output: true (Logical OR)
console.log(!true); // Output: false (Logical NOT)

5. Control Structures

Control structures determine the flow of the program. The primary control structures are if-else, switch, and loops (for, while, do-while).

Example:

// If-Else Statement
let grade = 85;
if (grade >= 90) {
    console.log("A grade");
} else if (grade >= 80) {
    console.log("B grade");
} else if (grade >= 70) {
    console.log("C grade");
} else {
    console.log("D grade");
}

// Switch Statement
grade = 85;
switch (grade) {
    case 90:
        console.log("A grade");
        break;
    case 85:
        console.log("B grade");
        break;
    case 70:
        console.log("C grade");
        break;
    default:
        console.log("Other grade");
}

// For Loop
for (let i = 0; i < 5; i++) {
    console.log(i);
}

// While Loop
let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}

// Do-While Loop
i = 0;
do {
    console.log(i);
    i++;
} while (i < 5);

6. Functions

Functions are blocks of code designed to perform a particular task. You can declare and call functions in JavaScript.

Example:

Top 10 Interview Questions & Answers on JavaScript Basic Syntax and Code Execution

1. What is JavaScript?

Answer: JavaScript (often abbreviated as JS) is a versatile programming language that is primarily used to make web pages interactive. It's executed on the client-side within the web browser but can also be run on the server-side using environments like Node.js.

2. How do you include JavaScript in an HTML document?

Answer: JavaScript can be included in an HTML document using the <script> tag. This tag can be placed in either the <head> or the <body> section:

  • Inside the <head>:
    <head>
        <script>
            alert("Hello World!");
        </script>
    </head>
    
  • Inside the <body>:
    <body>
        <script>
            console.log("This script runs after the page loads.");
        </script>
    </body>
    
  • Externally from an external file:
    <script src="script.js"></script>
    

where script.js is the file containing the JavaScript code.

3. What are the different types of data in JavaScript?

Answer: JavaScript supports several types of data, categorized into two main groups:

  • Primitive Types:
    • Number: e.g., 42, 3.14
    • String: e.g., "Hello", 'World'
    • Boolean: true, false
    • Null: representing a intentional absence of any object value, null
    • Undefined: a variable is declared but not assigned a value, undefined
    • Symbol: unique and immutable values (introduced in ES6)
  • Reference Types (Objects):
    • Object: e.g., {name: "Alice", age: 25}
    • Array: e.g., [1, 2, 3]
    • Function: function sayHi() {}
    • Date, RegExp, etc.

4. How do variables work in JavaScript?

Answer: Variables in JavaScript are used to store data values. They can be declared using:

  • var: function-scoped or globally-scoped
  • let: block-scoped (introduced in ES6)
  • const: block-scoped, for values that are not supposed to change

Example:

var x = 10;   // can be re-assigned and has function scope
let y = 20;   // can be re-assigned, block-scoped
const z = 30; // cannot be re-assigned, block-scoped

5. Explain the difference between == and === operators in JavaScript.

Answer: Both == (equality) and === (strict equality) operators are used to compare values, but they differ in how they handle type coercion:

  • == compares values after performing type coercion if necessary:
    console.log(5 == '5');  // true, because '5' is coerced to 5
    console.log(true == 1); // true, because true is coerced to 1
    
  • === compares both value and type, no type coercion:
    console.log(5 === '5'); // false, different types
    console.log(true === 1); // false, different types
    

6. What is a function in JavaScript, and how do you define one?

Answer: A function in JavaScript is a block of code designed to perform a particular task. Functions can be:

  • Function Declaration:
    function greet(name) {
        return "Hello, " + name + "!";
    }
    
  • Function Expression:
    const greet = function(name) {
        return "Hello, " + name + "!";
    };
    
  • Arrow Function (ES6+):
    const greet = (name) => {
        return "Hello, " + name + "!";
    };
    

7. How does JavaScript handle conditional statements?

Answer: JavaScript provides control structures to perform different actions based on conditions:

  • if...else:
    if (condition1) {
        // code to execute if condition1 is true
    } else if (condition2) {
        // code to execute if condition1 is false and condition2 is true
    } else {
        // code to execute if all conditions are false
    }
    
  • switch:
    switch (expression) {
        case value1:
            // code for value1
            break;
        case value2:
            // code for value2
            break;
        default:
            // code for no match
    }
    

8. Describe the basic structure of a loop in JavaScript.

Answer: JavaScript supports various types of loops to repeat a block of code until a condition is met:

  • for loop:
    for (let i = 0; i < 5; i++) {
        console.log(i);
    }
    
  • while loop:
    let i = 0;
    while (i < 5) {
        console.log(i);
        i++;
    }
    
  • do...while loop:
    let i = 0;
    do {
        console.log(i);
        i++;
    } while (i < 5);
    

9. What are arrays in JavaScript, and how can you manipulate them?

Answer: Arrays in JavaScript are used to store multiple values in a single variable. Common array methods include:

  • Creating an array:
    let fruits = ["apple", "banana", "cherry"];
    
  • Adding elements:
    fruits.push("date"); // adds "date" to the end
    fruits.unshift("apple"); // adds "apple" to the beginning
    
  • Removing elements:
    fruits.pop(); // removes the last element
    fruits.shift(); // removes the first element
    
  • Accessing elements:
    let firstFruit = fruits[0]; // returns "apple"
    
  • Iterating through arrays:
    fruits.forEach(fruit => {
        console.log(fruit);
    });
    

10. How does JavaScript handle code execution and the concept of event loops?

Answer: JavaScript is single-threaded but uses an event loop to handle asynchronous operations:

  • Code Execution: JavaScript engine follows a synchronous execution model, meaning it executes code line by line in the order it appears.
  • Event Loop: When asynchronous operations (like AJAX calls or setTimeout) are encountered, the JavaScript engine offloads them to the browser’s event loop. Once these operations complete, their callbacks are placed on the call stack to be executed.

Steps in the Event Loop:

  1. Execution Context: The JavaScript engine creates an execution context for the currently running code.
  2. Stack: Functions are pushed onto the call stack and are executed in a last-in, first-out (LIFO) order.
  3. Queue: Non-blocking operations and their callbacks are pushed into a queue (task queue, microtask queue).
  4. Event Loop: The event loop constantly checks the call stack and the task queue. If the stack is empty, it moves the next item from the queue to the stack for execution.

This mechanism allows JavaScript to perform multiple tasks concurrently and handle non-blocking operations efficiently.


You May Like This Related .NET Topic

Login to post a comment.