Getting Started with JavaScript.
Where to write JavaScript
You can write JavaScript directly in an HTML file within <script>
tags.
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<script>
// Your JavaScript code here
</script>
</body>
</html>
You can also create a separate .js
file and link it to your HTML file.
- index.html
- style.css
- app.js
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
//linking js file to HTML file
<script src='app.js'></script>
</body>
</html>
JavaScript Data types
In JavaScript, there are two main types of data: primitive data types and objects data types.
primitive: Primitive data types are simple data types that represent a single value. The primitive data types in JavaScript are: String, Number, Boolean, Null, Undefined.
JavaScript has dynamic typing: We do not have to manually define the data type of the value stored in a variable. Instead, data types are determined automatically.
To check the data type of a value in JavaScript, you can use the typeof operator. The typeof operator returns a string that represents the type of the value.
console.log(typeof "world")
//It will display String in the browser's console.
console.log(typeof 144)
//It will display Number in the browser's console.
console.log(typeof true)
//It will display Boolean in the browser's console.
In JavaScript, strings are immutable, which means that you cannot modify individual characters of a string.
let name = "John";
name = "Jane"; // allowed
name[0] = "J"; // not allowed
In this example, the name variable is assigned the value John, which is a string. The value of the name variable can be changed by assigning a new value to it (e.g. name = "Jane"). However, you cannot change the individual characters of the string directly.
Objects: Objects are complex data types that can contain multiple values and properties. Objects are used to represent real-world entities or abstract concepts with multiple characteristics. Objects are created using the syntax and can contain multiple properties, which are represented as key-value pairs. For example:
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
isEmployed: true
};
In this example, the person object has four properties: firstName, lastName, age, and isEmployed. Each property has a key (the property name) and a value (the property value).
You can access the properties of an object using the . notation or the [] notation:
console.log(person.firstName);
//It will display John in the browser's console.
console.log(person["lastName"]);
//It will display Doe in the browser's console.
Objects are mutable, which means that you can change their properties and values at any time.
Javascript Control Structures
if statement: The if statement is used to execute a block of code if a condition is true. For example:
let x = 10;
if (x > 0) {
console.log("x is positive");
//This code will output "x is positive" to the console, because the condition x > 0 is true.
}
If-else statement: You can also use an else clause to specify a block of code that should be executed if the condition is false:
let x = 10;
if (x > 0) {
console.log("x is positive");
//This code will output "x is positive" to the console, because the condition x > 0 is true.
}else {
console.log("x is not positive");
//This code will output "x is not positive" to the console, if the condition x > 0 is false.
}
Switch statement: The switch statement is used to execute a block of code based on the value of a variable. For example:
let x = "red";
switch (x) {
case "red":
console.log("x is red");
break;
case "blue":
console.log("x is blue");
break;
default:
console.log("x is neither red nor blue");
}
This code will output "x is red" to the console, because the value of x is "red". The switch statement is often used as an alternative to a series of if statements, when you have to check multiple values.
Javascript Loops: In JavaScript, a loop is a control flow statement that allows you to execute a block of code repeatedly. There are several types of loops in JavaScript:
for Loop: The for loop is used to execute a block of code a specified number of times. It has the following syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
The initialization statement is executed only once at the beginning of the loop. It is used to initialize a counter variable. The condition is evaluated at the beginning of each iteration. If the condition is true, the loop continues. If the condition is false, the loop terminates. The increment/decrement statement is executed at the end of each iteration. It is used to update the counter variable.
A counter variable is a variable that keeps track of a numerical value. It's often used to count the number of times something happens or to iterate through a set of data.
an example of the for loop
for (let i = 1; i <= 10; i++) {
console.log(i);
//This code will display 1-10 in the browser console.
//It display that because initially the value of i is 1, 1 is add to i using (i++) and it is made to repeat itself using (for) but not exceeding 10 according to (i<=10).
}
While Loop: The while loop is used to execute a block of code as long as a certain condition is true. It has the following syntax:
while (condition) {
// code to be executed
}
The condition is evaluated at the beginning of each iteration. If the condition is true, the loop continues. If the condition is false, the loop terminates.
an example of the while loop
let i = 1; // Initialize a variable 'i' with the value 1.
while (i <= 10) { // Start a while loop that runs as long as 'i' is less than or equal to 10.
console.log( i);// Log the message "this is the no X" to the console, where X is the current value of 'i'.
i++; // Increment the value of 'i' by 1.
}
do-while Loop: The do-while loop is similar to the while loop, but the block of code is always executed at least once. It has the following syntax:
do {
// code to be executed
} while (condition);
The condition is evaluated at the end of each iteration. If the condition is true, the loop continues. If the condition is false, the loop terminates.
an example of the do-while loop
let i = 1; // Initialize a variable 'i' with the value 1
do {
console.log(i); // Print the current value of 'i' to the console
i++; // Increment the value of 'i' by 1
} while (i <= 10); // Continue the loop as long as 'i' is less than or equal to 10
for-in Loop: The for-in loop is used to iterate over the properties of an object. It has the following syntax:
for (variable in object) {
// code to be executed
}
The variable takes on the value of each property in the object, and the loop continues until all properties have been processed.
an example of the for-in loop
// Create an object named 'person' with three properties: name, age, and job
let person = {
name: "John", // The 'name' property with the value "John"
age: 30, // The 'age' property with the value 30
job: "developer" // The 'job' property with the value "developer"
};
// Use a for-in loop to iterate over the properties of the 'person' object
for (let prop in person) {
// Inside the loop, 'prop' will be assigned the name of each property in the object in turn
// Log the property name and its value to the console in the format: "property: value"
console.log(prop + ": " + person[prop]);
// 'person[prop]' accesses the value of the property named 'prop' in the 'person' object
}
// The expected output will be:
// name: John
// age: 30
// job: developer
for-of Loop: The for-of loop is a modern way to iterate over the values of an iterable object, such as an array or a string. It was introduced in ECMAScript 6 (ES6) and has the following syntax:
for (variable of object) {
// code to be executed
}
The variable takes on the value of each element in the object, and the loop continues until all elements have been processed.
an example of the for-of loop
// Define an array called 'numbers' with five elements: 1, 2, 3, 4, and 5
let numbers = [1, 2, 3, 4, 5];
// Use a 'for...of' loop to iterate over each element in the 'numbers' array
for (let num of numbers) {
// Inside the loop, log the current element (num) to the console
console.log(num);
}
Break and continue statements in Loops: The break and continue statements are used to control the flow of a loop in JavaScript. The break statement is used to exit a loop prematurely. It can be used in any type of loop, such as a for, while, or do-while loop. When the break statement is encountered, the loop is immediately terminated and the flow of control moves to the statement following the loop.
break: Here is an example of a for loop with a break statement:
for (let i = 0; i < 10; i++) {
if (i == 5) {
break; // If i is 5, break the loop and stop further iterations.
}
console.log(i);
}
In this example, the loop will terminate when i is 5 and the break statement is encountered. The output will be the numbers 0 through 4.
continue: The continue statement is used to skip the rest of the current iteration of a loop and move on to the next one. It can also be used in any type of loop. When the continue statement is encountered, the loop's counter is updated and the flow of control returns to the loop's condition.
let i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue;
}
console.log(i);
}
In this example, the continue statement will skip the rest of the current iteration when i is even and move on to the next iteration. The output will be the odd numbers 1 through 9
Javascript Functions
Javascript Function types
Function declarations: Function declarations are created using the function keyword, followed by the function name and a set of parentheses that may include parameters. The function body is placed between curly braces. Function declarations are hoisted, which means that they are available for use throughout your code, even before they are defined. Here is an example of a function declaration:
function sayHello(name) {
console.log("Hello, " + name + "!");
}
Function expressions: Function expressions are created by assigning a function to a variable. They are not hoisted, which means that they are not available for use until after they are defined. Here is an example of a function expression:
var sayHello = function(name) {
console.log("Hello, " + name + "!");
}
Arrow functions: Arrow functions are a modern way to write functions in JavaScript. They are created using the => syntax and are concise and easy to read. Arrow functions do not have their own this value and cannot be used as constructors. Here is an example of an arrow function:
const sayHello = (name) => {
console.log("Hello, " + name + "!");
};
Calling(Invoking Functions): To call a function in JavaScript, you simply need to use its name followed by a set of parentheses that may include arguments. For example:
function sayHello(name) {
console.log("Hello, " + name + "!");
}
//Calling the function
sayHello("John");
//It will display Hello John! on the browser console
function parameters: are the names listed in the function definition and are used to receive input values (arguments) when the function is called. The function can then use these parameters to perform its task. For example:
function add(a, b) {
return a + b;
}
Sum = add(1, 2);
console.log(sum);
//It will the result after adding 1 and 2 which 3.
In this example, the add function accepts two parameters, a and b, and returns their sum. When the function is called with the arguments 1 and 2, it returns the value 3.
A 'return statement' is used within a function to specify the value that the function should output when it is called. The return statement ends the function's execution and specifies the value that should be returned to the caller. If a function does not have a return statement, it will return the special value undefined.
ANATOMY OF A FUNCTION:
