Skip to main content

Command Palette

Search for a command to run...

Running Your First JavaScript Code

Published
18 min readView as Markdown
B

Student | Tech enthusiast | Aspiring software developer


  • Create a Folder:

    • Create a new folder on your computer and name it practicejs.
  • Create an HTML File:

    • Inside the practicejs folder, create a new file and name it index.html.
  • Add Boilerplate Code:

    • Open index.html with a text editor (like VS Code, Sublime Text, or Notepad).

      * Add the following boilerplate HTML code to the file:

      •   <!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>My First JavaScript Code</title>
          </head>
          <body>
              <h1>Hello, JavaScript!</h1>
              <script>
                  // Your JavaScript code will go here
                  console.log('Hello, world!');
              </script>
          </body>
          </html>
        

        * Open in Browser:

        * * Save the file and open index.html in your web browser. You can do this by double-clicking the file or right-clicking it and selecting "Open with" and then choosing your browser.

        * Inspect and Open Console:

        * * Right-click anywhere on the page and select "Inspect" (or press Ctrl+Shift+I on Windows/Linux or Cmd+Option+I on Mac).

        *

        Click on the "Console" tab in the Developer Tools that open up.

        * View Your First JavaScript Output:

        * * You should see the message Hello, world! printed in the console.

        *

Variable In Javascript


What is a Variable in JavaScript?

A variable in JavaScript is a container for storing data values. It allows you to save a value and use it later in your program. Variables can hold different types of data, such as numbers, strings, objects, and more.

Variable Assignment and Logging

a = 10;
console.log('a');
console.log(a);
  • a = 10;: This line assigns the value 10 to the variable a. Since a is not declared with var, let, or const, it becomes a global variable.

  • console.log('a');: This line prints the string 'a' to the console. It does not print the value of the variable a, but the literal string 'a'.

  • console.log(a);: This line prints the value of the variable a to the console. Since a has been assigned the value 10, it will print 10.

Assigning and Using Another Variable

a = 10;
b = a;
console.log(a);
  • a = 10;: This line reassigns the value 10 to the variable a. This doesn't change anything since a was already 10.

  • b = a;: This line assigns the value of a (which is 10) to the variable b. Now, b also holds the value 10.

  • console.log(a);: This line prints the value of the variable a to the console. It will print 10.

Reassigning the Variable a

a = 10;
a = 5;
console.log(a);
  • a = 10;: This line assigns the value 10 to the variable a again.

  • a = 5;: This line reassigns the value 5 to the variable a, overwriting the previous value 10.

  • console.log(a);: This line prints the current value of the variable a to the console. Since a has been reassigned to 5, it will print 5.

Variable Declarations in JavaScript: var


For var:

Variable a Declarations and Logging

var a = 10;
var a = 20;
var a = 30;

console.log(a);
  • var a = 10;: This line declares a variable a and assigns it the value 10.

  • var a = 20;: This line re-declares the variable a and assigns it a new value 20. In JavaScript, var allows redeclaration of the same variable within the same scope.

  • var a = 30;: This line re-declares the variable a again and assigns it a new value 30. Each time, the previous value is overwritten.

  • console.log(a);: This line prints the current value of a, which is 30. This is because the last assignment to a was 30.

Variable b Declaration and Block Scope

{
    var b = 10;
    console.log(b);
}
b = 20;

console.log(b);

Block Scope:

{
    var b = 10;
    console.log(b);
}
  • var b = 10;: This line declares a variable b and assigns it the value 10. Even though b is declared inside a block, because var is used, b is function-scoped or globally-scoped, not block-scoped.

  • console.log(b);: This line prints the value of b, which is 10.

Reassigning b:

b = 20;

b = 20;: This line reassigns the value of b to 20. Since b was declared with var, it is accessible outside the block, and this reassignment is valid.

Logging b:

console.log(b);
    • console.log(b);: This line prints the current value of b, which is now 20.

let


The let keyword in JavaScript is used to declare variables that are block-scoped. This means that a variable declared with let is only accessible within the block it was declared in, and it cannot be redeclared in the same scope.

Let's break down and explain the provided JavaScript code step by step.

Variable a Declaration and Reassignment

let a = 10;
a = 20;
console.log(a);
  • let a = 10;: This line declares a variable a with the value 10. The scope of a is the block in which it is declared.

  • a = 20;: This line reassigns the value of a to 20. Reassignment of let variables is allowed.

  • console.log(a);: This line prints the value of a to the console, which is 20.

Block Scope with let for Variable b

let b = 20;
{ 
    let b = 30;
    console.log(b);
}

console.log(b);

let b = 20;: This line declares a variable b with the value 20. The scope of b is the block in which it is declared.

Block Scope:

{
    let b = 30;
    console.log(b);
}
  • let b = 30;: This line declares a new variable b inside a block with the value 30. This b is different from the b declared outside the block. The scope of this b is limited to this block.

  • console.log(b);: This line prints the value of b within the block, which is 30.

Outside the Block:

console.log(b);

console.log(b);: This line prints the value of the variable b declared outside the block. The value of this b is still 20 because the block-scoped b did not affect it.

Const


The const keyword in JavaScript is used to declare variables that are block-scoped and cannot be reassigned. This means that once a variable is assigned a value using const, it cannot be changed or reassigned. However, the properties of objects and elements of arrays declared with const can still be modified.

Let's break down and explain the provided JavaScript code step by step.

Variable a Declaration and Attempted Reassignment

const a = 10;
a = 20;
console.log(a);
  • const a = 10;: This line declares a variable a with the value 10. The scope of a is the block in which it is declared. const variables must be initialized at the time of declaration.

  • a = 20;: This line attempts to reassign the value of a to 20. Since a was declared with const, this will throw a TypeError because const variables cannot be reassigned.

  • console.log(a);: This line would not be reached due to the error thrown in the previous line.

Block Scope with const for Variable b

const b = 20;

{
    const b = 30;
    console.log(b);
}

console.log(b);

const b = 20;: This line declares a variable b with the value 20. The scope of b is the block in which it is declared.

Block Scope:

{
    const b = 30;
    console.log(b);
}
  • const b = 30;: This line declares a new variable b inside a block with the value 30. This b is different from the b declared outside the block. The scope of this b is limited to this block.

  • console.log(b);: This line prints the value of b within the block, which is 30.

Outside the Block:

console.log(b);

​​​​​​​console.log(b);: This line prints the value of the variable b declared outside the block. The value of this b is still 20 because the block-scoped b did not affect it.

Data type


In JavaScript, a datatype is a classification that specifies which type of value a variable can hold. Here are the types of data types in JavaScript:

  1. Primitive Data Types:

    • Number

    • String

    • Boolean

    • Undefined

    • Null

  2. Non-Primitive (Reference) Data Types:

    • Array

    • Object

Primitive Data Types


Primitive Data Types

Primitive data types are immutable and include the following:

  1. Number:

    • Represents both integer and floating-point numbers.

      • Example

      •    let age = 25;
           let pi = 3.14;
        
  2. String:

  3. Represents a sequence of characters enclosed in single quotes ('), double quotes ("), or backticks (` ).

  4. Example:

let greeting = "Hello, World!";
let name = 'John Doe';
let templateLiteral = `This is a string`;

Boolean:

  • Represents logical values: true or false.

  • Example

let isJavaScriptFun = true;
let isItRaining = false;

Undefined:

  • Represents a variable that has been declared but not assigned a value.

  • Example

let x;
console.log(x); // undefined

Null:

  • Represents the intentional absence of any object value.

  • Example

let y = null;

Non-Primitive Data Types

Non-primitive data types can hold collections of values and more complex entities.

  1. Object:

    • Represents collections of properties, which are key-value pairs.

    • Example:

  2.   let person = {
          name: 'Alice',
          age: 30,
          isStudent: false
      };
    

Array:

  • A special type of object used for storing ordered collections of values.

  • Example

let numbers = [1, 2, 3, 4, 5];
let mixedArray = [1, 'two', true, null];

Function:

  • Functions are objects that can be called to perform tasks or return values.

  • Example

function greet() {
    return "Hello!";
}

Non Primitive (object)


Object

In JavaScript, an object is a collection of properties, where each property is defined as a key-value pair. Objects allow you to group related data and functions together, making it easier to manage and manipulate complex data structures.

<script>
    const Student = {
        name: "Bisesh Adhikari",
        Semester: "6th semester",
        Roll_no: 21
    };
</script>

In this example:

  • Student is an object.

  • The object has three properties:

    • name: This property has a value of "Bisesh Adhikari", which is a string.

    • Semester: This property has a value of "6th semester", which is a string.

    • Roll_no: This property has a value of 21, which is a number.

You can access the properties of the Student object using dot notation or bracket notation. For example:

console.log(Student.name); // Output: Bisesh Adhikari
console.log(Student["Semester"]); // Output: 6th semester
console.log(Student.Roll_no); // Output: 21

The Student object not only contains properties but also a method. A method is a function that is a property of an object. This demonstrates how objects can encapsulate both data and behavior.

<script>
    const Student = {
        name: "Bisesh Adhikari",
        Semester: "6th semester",
        Roll_no: 21,
        write_code: function() { 
            console.log("write code");
        }
    };

    Student.write_code(); // Calls the write_code method
</script>

Explanation

  1. Properties:

    • name: Holds the value "Bisesh Adhikari", a string representing the student's name.

      • Semester: Holds the value "6th semester", a string representing the student's current semester.

      • Roll_no: Holds the value 21, a number representing the student's roll number.

  2. Method:

    • write_code: This is a method of the Student object. It is defined as a function that logs the string "write code" to the console when called.

Using the Method

The method write_code is called using the following syntax:

Student.write_code();

Conditional Statements


Conditional statements are used to perform different actions based on different conditions. In JavaScript, the most common conditional statements are if, else if, and else.

1. if Statement

The if statement is used to specify a block of code that will be executed if a specified condition is true.

if (condition) {
  // code to be executed if the condition is true
}

Example

let age = 18;

if (age >= 18) {
  console.log("You are an adult.");
}

In this example, the message "You are an adult." will be printed to the console if age is greater than or equal to 18.

2. else Statement

The else statement specifies a block of code to be executed if the same condition is false.

if (condition) {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
}

For example:

let age = 16;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

3. else if Statement

The else if statement specifies a new condition to test if the first condition is false.

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition1 is false and condition2 is true
} else {
  // code to be executed if both condition1 and condition2 are false
}

Example:

let score = 85;

if (score >= 90) {
  console.log("You got an A.");
} else if (score >= 80) {
  console.log("You got a B.");
} else {
  console.log("You need to study more.");
}

practical example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Voting Eligibility Checker</title>
</head>
<body>
  <h1>Voting Eligibility Checker</h1>
  <script src="script.js"></script>
</body>
</html>
// Ask the user for their age
let age = prompt("Enter your age:");

// Convert the input to a number
†i

// Check if the user is eligible to vote
if (age >= 18) {
  console.log("You are eligible to vote!");
  document.write("<p>You are eligible to vote!</p>");
} else {
  console.log("You are not eligible to vote yet.");
  document.write("<p>You are not eligible to vote yet.</p>");
}

While Loop


Let's break down and analyze the given code snippets, focusing on the repetition and the use of loops.

Before Using the Loop

print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")

In this snippet, the same line of code print("Bisesh Adhikari") is repeated multiple times. Specifically, it is repeated nine times. This approach works but is not efficient or scalable, especially if you need to print the same statement many times.

After Using the Loop

let count = 0;
while(count <= 10) { 
    print("Bisesh Adhikari");
    count++;
}

Here, a loop is introduced to handle the repetition.

Explanation:

  1. Initialization: let count = 0;

    • A variable count is initialized to 0.
  2. Condition: while(count <= 10)

    • The while loop will run as long as the condition count <= 10 is true. Since count starts at 0 and goes up to 10, the loop will execute 11 times (from 0 to 10 inclusive).
  3. Body of the Loop:

    • print("Bisesh Adhikari");

      • The statement print("Bisesh Adhikari"); will be executed in each iteration of the loop.
    • count++;

      • After printing, the count variable is incremented by 1.

Comparison

  • Before Using the Loop:

    • Code is longer and repetitive.

    • Not efficient for a larger number of repetitions.

    • Harder to maintain and prone to errors if the number of repetitions needs to change.

  • After Using the Loop:

    • Code is shorter and more readable.

    • Efficient and scalable.

    • Easier to maintain; changing the number of repetitions requires only a single change in the loop condition.

In summary, using a loop to handle repetitive tasks makes the code more efficient, readable, and maintainable. In this case, the while loop is used to print the string "Bisesh Adhikari" 11 times, which is more concise and easier to manage than writing the print statement multiple times manually.

do while loop


General Explanation of a do...while Loop

In general terms, a do...while loop is a type of loop that ensures the block of code inside the loop is executed at least once before the condition is tested. This is useful when you want the code to run at least one time regardless of the condition.

Explanation of a do...while Loop in JavaScript

In JavaScript, a do...while loop is used to execute a block of code at least once and then continue to execute it as long as a specified condition evaluates to true. The condition is checked after the code block has been executed.

Syntax

do {
    // code block to be executed
} while (condition);

Example

Let's see a practical example of how a do...while loop works in JavaScript:

let count = 0;
do {
    console.log("Bisesh Adhikari");
    count++;
} while (count < 5);

Explanation of the Example

  1. Initialization:

    • let count = 0;

      • A variable count is initialized to 0.
  2. Loop Execution:

    • The code block inside the do section (console.log("Bisesh Adhikari"); count++;) is executed first, regardless of the condition.

    • This means "Bisesh Adhikari" will be printed, and count will be incremented by 1.

  3. Condition Check:

    • After executing the code block, the condition count < 5 is checked.

    • If the condition is true, the loop will execute the code block again.

    • This process repeats until the condition evaluates to false.

For loop


General Explanation of a for Loop

A for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It is commonly used when the number of iterations is known before entering the loop.

Explanation of a for Loop in JavaScript

In JavaScript, a for loop repeats a block of code a specified number of times. It consists of three parts: initialization, condition, and increment/decrement.

Example

Let's see a practical example of how a for loop works in JavaScript:

for (let i = 0; i < 5; i++) {
    console.log("Bisesh Adhikari");
}

Explanation of the Example

  1. Initialization:

    • let i = 0;

      • A variable i is initialized to 0. This is executed once at the start of the loop.
  2. Condition:

    • i < 5;

      • The loop runs as long as this condition is true. If i is less than 5, the loop continues.
  3. Increment/Decrement:

    • i++

      • After each iteration of the loop, i is incremented by 1.
  4. Code Block:

    • console.log("Bisesh Adhikari");

      • This code block is executed each time the loop runs.

Using a for Loop with an Array

A for loop is often used to iterate over the elements of an array. Here's how you can do it:

Example with Array

const names = ["Bisesh", "Adhikari", "John", "Doe"];
for (let i = 0; i < names.length; i++) {
    console.log(names[i]);
}

Explanation of the Example

  1. Initialization:

    • let i = 0;

      • A variable i is initialized to 0.
  2. Condition:

    • i < names.length;

      • The loop runs as long as i is less than the length of the names array.
  3. Increment/Decrement:

    • i++

      • After each iteration, i is incremented by 1.
  4. Code Block:

    • console.log(names[i]);

      • This code block logs the current element of the array names to the console.

Summary

  • for Loop: Used when the number of iterations is known.

  • Syntax: Includes initialization, condition, and increment/decrement.

  • Array Iteration: The for loop is commonly used to iterate over arrays by using the array's length in the condition.

Functions In js


Introduction to Functions

Why Do We Need Functions?

Functions help to organize and reuse code. They allow you to divide your program into manageable pieces and reduce repetition. Here’s a simple example to illustrate the need for functions:

Without Functions:

# Calculate the square of numbers without using functions
number1 = 5
square1 = number1 * number1
print(f"The square of {number1} is {square1}")

number2 = 10
square2 = number2 * number2
print(f"The square of {number2} is {square2}")

number3 = 15
square3 = number3 * number3
print(f"The square of {number3} is {square3}")

With Functions:

# Define a function to calculate the square of a number
def calculate_square(number):
    square = number * number
    return square

# Call the function for different numbers
print(f"The square of 5 is {calculate_square(5)}")
print(f"The square of 10 is {calculate_square(10)}")
print(f"The square of 15 is {calculate_square(15)}")

Components of a Function

  1. Function Definition:

    • You define a function using the def keyword, followed by the function name and parentheses containing parameters.
  2. Parameters and Arguments:

    • Parameters are the variables listed inside the parentheses in the function definition.

    • Arguments are the actual values passed to the function when it is called.

  3. Function Body:

    • The code inside the function that performs the task. It is indented.
  4. Return Statement:

    • The return statement is used to send a result back to the caller of the function.

Example: Function Basics

Here’s an example demonstrating the basic structure and usage of a function:

# Define a function with parameters
def greet(name):
    # Function body
    message = f"Hello, {name}!"
    return message

# Call the function with an argument
greeting = greet("Alice")
print(greeting)  # Output: Hello, Alice!

More on Calling Functions

Functions can be called multiple times with different arguments:

print(greet("Bob"))    # Output: Hello, Bob!
print(greet("Carol"))  # Output: Hello, Carol!

Functions with Multiple Parameters

You can define functions with multiple parameters:

def add(a, b):
    result = a + b
    return result

print(add(3, 4))  # Output: 7
print(add(10, 20))  # Output: 30

Return Statement

The return statement ends the function execution and specifies what value to return to the caller. If no return statement is used, the function returns None.

def multiply(a, b):
    return a * b

result = multiply(4, 5)
print(result)  # Output: 20

Summary

  • Functions are used to organize and reuse code.

  • Parameters are placeholders in the function definition.

  • Arguments are the actual values passed to the function.

  • The return statement sends a result back to the caller.

Functions are fundamental in programming as they make code more modular, readable, and maintainable.

Arrow Functions


Arrow functions, also known as lambda functions, are a shorthand way of defining small, anonymous functions. They are commonly used in languages like JavaScript, Python, and others for creating concise function expressions. Here, we will cover arrow functions in both JavaScript and Python.

Arrow Functions in JavaScript

In JavaScript, arrow functions provide a compact syntax for writing functions. They are especially useful for inline functions.

Syntax

The basic syntax of an arrow function is as follows:

// Traditional function expression
let traditionalFunction = function(parameter1, parameter2) {
    // Function body
    return parameter1 + parameter2;
};

// Arrow function expression
let arrowFunction = (parameter1, parameter2) => {
    // Function body
    return parameter1 + parameter2;
};

If the function body contains only a single expression, you can omit the curly braces {} and the return statement:

let arrowFunction = (parameter1, parameter2) => parameter1 + parameter2;

Examples

  1. Simple Arrow Function:
let greet = name => `Hello, ${name}!`;
console.log(greet("Alice"));  // Output: Hello, Alice!

Arrow Function with Multiple Parameters:

let add = (a, b) => a + b;
console.log(add(3, 4));  // Output: 7
  1. Arrow Function with No Parameters:
let sayHello = () => "Hello, World!";
console.log(sayHello());  // Output: Hello, World!

square of a number

        // Using arrow function display the square of a number
        let square = (a)=>a*a

        console.log(square(10))

More from this blog

Bisesh's Blog

24 posts