Running Your First JavaScript Code
Student | Tech enthusiast | Aspiring software developer
Create a Folder:
- Create a new folder on your computer and name it
practicejs.
- Create a new folder on your computer and name it
Create an HTML File:
- Inside the
practicejsfolder, create a new file and name itindex.html.
- Inside the
Add Boilerplate Code:
Open
index.htmlwith 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.htmlin 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+Ion Windows/Linux orCmd+Option+Ion 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 value10to the variablea. Sinceais not declared withvar,let, orconst, 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 variablea, but the literal string'a'.console.log(a);: This line prints the value of the variableato the console. Sinceahas been assigned the value10, it will print10.
Assigning and Using Another Variable
a = 10;
b = a;
console.log(a);
a = 10;: This line reassigns the value10to the variablea. This doesn't change anything sinceawas already10.b = a;: This line assigns the value ofa(which is10) to the variableb. Now,balso holds the value10.console.log(a);: This line prints the value of the variableato the console. It will print10.
Reassigning the Variable a
a = 10;
a = 5;
console.log(a);
a = 10;: This line assigns the value10to the variableaagain.a = 5;: This line reassigns the value5to the variablea, overwriting the previous value10.console.log(a);: This line prints the current value of the variableato the console. Sinceahas been reassigned to5, it will print5.
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 variableaand assigns it the value10.var a = 20;: This line re-declares the variableaand assigns it a new value20. In JavaScript,varallows redeclaration of the same variable within the same scope.var a = 30;: This line re-declares the variableaagain and assigns it a new value30. Each time, the previous value is overwritten.console.log(a);: This line prints the current value ofa, which is30. This is because the last assignment toawas30.
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 variableband assigns it the value10. Even thoughbis declared inside a block, becausevaris used,bis function-scoped or globally-scoped, not block-scoped.console.log(b);: This line prints the value ofb, which is10.
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 ofb, which is now20.
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 variableawith the value10. The scope ofais the block in which it is declared.a = 20;: This line reassigns the value ofato20. Reassignment ofletvariables is allowed.console.log(a);: This line prints the value ofato the console, which is20.
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 variablebinside a block with the value30. Thisbis different from thebdeclared outside the block. The scope of thisbis limited to this block.console.log(b);: This line prints the value ofbwithin the block, which is30.
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 variableawith the value10. The scope ofais the block in which it is declared.constvariables must be initialized at the time of declaration.a = 20;: This line attempts to reassign the value ofato20. Sinceawas declared withconst, this will throw a TypeError becauseconstvariables 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 variablebinside a block with the value30. Thisbis different from thebdeclared outside the block. The scope of thisbis limited to this block.console.log(b);: This line prints the value ofbwithin the block, which is30.
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:
Primitive Data Types:
NumberStringBooleanUndefinedNull
Non-Primitive (Reference) Data Types:
Array
Object
Primitive Data Types
Primitive Data Types
Primitive data types are immutable and include the following:
Number:
Represents both integer and floating-point numbers.
Example
let age = 25; let pi = 3.14;
String:
Represents a sequence of characters enclosed in single quotes (
'), double quotes ("), or backticks (`).Example:
let greeting = "Hello, World!";
let name = 'John Doe';
let templateLiteral = `This is a string`;
Boolean:
Represents logical values:
trueorfalse.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.
Object:
Represents collections of properties, which are key-value pairs.
Example:
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:
Studentis 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 of21, 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
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 value21, a number representing the student's roll number.
Method:
write_code: This is a method of theStudentobject. 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:
Initialization:
let count = 0;- A variable
countis initialized to0.
- A variable
Condition:
while(count <= 10)- The
whileloop will run as long as the conditioncount <= 10is true. Sincecountstarts at0and goes up to10, the loop will execute 11 times (from 0 to 10 inclusive).
- The
Body of the Loop:
print("Bisesh Adhikari");- The statement
print("Bisesh Adhikari");will be executed in each iteration of the loop.
- The statement
count++;- After printing, the
countvariable is incremented by1.
- After printing, the
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
Initialization:
let count = 0;- A variable
countis initialized to0.
- A variable
Loop Execution:
The code block inside the
dosection (console.log("Bisesh Adhikari"); count++;) is executed first, regardless of the condition.This means "Bisesh Adhikari" will be printed, and
countwill be incremented by1.
Condition Check:
After executing the code block, the condition
count < 5is 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
Initialization:
let i = 0;- A variable
iis initialized to0. This is executed once at the start of the loop.
- A variable
Condition:
i < 5;- The loop runs as long as this condition is
true. Ifiis less than5, the loop continues.
- The loop runs as long as this condition is
Increment/Decrement:
i++- After each iteration of the loop,
iis incremented by1.
- After each iteration of the loop,
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
Initialization:
let i = 0;- A variable
iis initialized to0.
- A variable
Condition:
i < names.length;- The loop runs as long as
iis less than the length of thenamesarray.
- The loop runs as long as
Increment/Decrement:
i++- After each iteration,
iis incremented by1.
- After each iteration,
Code Block:
console.log(names[i]);- This code block logs the current element of the array
namesto the console.
- This code block logs the current element of the array
Summary
forLoop: Used when the number of iterations is known.Syntax: Includes initialization, condition, and increment/decrement.
Array Iteration: The
forloop 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
Function Definition:
- You define a function using the
defkeyword, followed by the function name and parentheses containing parameters.
- You define a function using the
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.
Function Body:
- The code inside the function that performs the task. It is indented.
Return Statement:
- The
returnstatement is used to send a result back to the caller of the function.
- The
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
- 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
- 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))

