0% found this document useful (0 votes)
16 views32 pages

Scripting Languages_4

This document serves as an introduction to JavaScript, covering its syntax, comments, variables, data types, and basic operations. It explains how to define variables using 'let' and 'const', the differences between them, and various data types such as numbers, strings, booleans, and arrays. Additionally, it discusses mathematical operations, comparison operations, and the importance of understanding assignment and increment/decrement operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views32 pages

Scripting Languages_4

This document serves as an introduction to JavaScript, covering its syntax, comments, variables, data types, and basic operations. It explains how to define variables using 'let' and 'const', the differences between them, and various data types such as numbers, strings, booleans, and arrays. Additionally, it discusses mathematical operations, comparison operations, and the importance of understanding assignment and increment/decrement operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Scripting Languages

4. Introduction to JavaScript
(Part I)
2024, Spring Semester

Kutaisi International University


Syntax
JavaScript follows a default syntax with parentheses, curly brackets, and semicolons.
In JavaScript, you don't need to define a main function as required in languages like C, C++, Java, etc. You can directly
write your code:
console.log("Hello, user!");

• console.log() method. serves the purpose of printing values in the console.


•Following that, we place "Hello, user!" within this method, enclosed in parentheses ().
•The quotes (" or ') serve as indicators to JavaScript, signifying that Hello, user! is plain text and not a function or any other program-related keyword.
•Lastly, the semicolon (;) functions as the command terminator, marking the conclusion of a command.

Comments
Single-line Comments
you need to add // before the code on the line you wish to comment out: Also, we can add the comment at the end of the line.

console.log("Line 1"); console.log("Part 1.1"); console.log("Part 1.2");


// console.log("Line 2"); console.log("Part 2.1"); // console.log("Part 2.2")
console.log("Line 3"); console.log("Part 3.1"); console.log("Part 3.2");
Multi-line Comments
Multi-line comments start with /* and end with */. Any code enclosed within them is commented out:

console.log("Line 1");
console.log("Line 2");
/*
console.log("Line 4");
console.log("Line 5");
console.log("Line 6");
console.log("Line 7");
console.log("Line 8");
console.log("Line 9");
*/
console.log("Line 11");
Variables and Data Types
Variables
Before using variables, they must be defined. To define a variable, use the let keyword and choose a name for it:

let variableName;
Variable names should follow the camelCase style. camelCase means that words are written together without spaces, and each word (except the first) is
capitalized.
You can assign a value to a variable using the assignment operator ( =):

let x; or let x = 13;


x = 5;

Using Variables

let word = "VariableText"; // the variable value is the


"VariableText"

console.log("ValueText"); // print the value


console.log(word); // print the variable value
let numb;
numb = 100;
console.log(numb);

numb = 100 + 20;


console.log(numb);

const
The primary difference between let and const is that variables created using const cannot change their values, whereas using the let keyword allows changes to the
variable's value.

const myNumber = 10;


Let's compare the behavior of variables using let and const. Take a look at the following example where we can change the value of the a variable:
// a variable changing
let a = 5; In contrast, let's examine the behavior of the b variable. We will encounter an error: TypeError: Assignment to a constant variable.
console.log(a)
// a constant changing
const b = 7;
a = 10;
console.log(b);
console.log(a)
b = 8;
console.log(b);
Usage
Constants are used as immutable variables. You can define a constant once and use it multiple times.
Constants provide data integrity while allowing for quick refactoring.

Refactoring involves making structural changes to the code, such as modifying values, variable/function names, and
more.

const maxHeight = 250;


console.log(maxHeight - 15);
console.log(maxHeight - 12);
console.log(maxHeight - 5);
console.log(maxHeight - 13);
console.log(maxHeight - 22);
console.log(maxHeight - 52);
Data Types Overview

The Data Type tells the interpreter how to work with the data.

Let's look at the difference in the interpreter behavior:

// First case
console.log("123" + "123");

// Second case
console.log(123 + 123);

typeof()
The typeof() operator returns a string indicating the type of the operand's value.

let a = 15;
console.log(typeof 23);
console.log(typeof a);

const b = "today";
console.log(typeof "word");
console.log(typeof b);
Number
The number data type is used for calculations, counters, mathematical operations, and more.
Unlike other programming languages, JavaScript uses the number type instead of separate int and float types.

console.log(typeof(15.25));
console.log(typeof(211));

console.log(typeof(22 + 251));
console.log(typeof(26 / 342));

The typeof operator only determines the data type of the result, not the performed operations.
String

The string data type is used to change, print, and pass text to other programs.
let str = "Hello! I'm String, and I should help you to work with text!";
console.log(str);

To identify the string in the code, we should use single or double quotes (e.g., 'some text' or "some text")

console.log("text");
console.log('text');

console.log("console.log('text')");
console.log('console.log("text")');

console.log(typeof("10"));
Boolean

The boolean data type is used for logical operations. It has two values: true and false. Booleans are used to check conditions, as we'll describe later.
Booleans allow you to control code execution and direct it along different paths.
To create a boolean value, use the true or false values:

console.log(true);
console.log(false);

console.log(typeof(true));
console.log(typeof(false));

console.log(25 > 15);


console.log(15 > 25);
null
In JavaScript, the null type represents "nothing" or the absence of data.

let variable = null 1.null is distinct from undefined.


2.We use null when we need to signify the absence of data or to pass the
3.concept of "nothing" to another part of the program.
console.log("Some data 1")
console.log(variable)
console.log("Some data 2")
Array
The array is the most useful data structure.
Creating an Array
To create an array, use square brackets []: const arr = [];
This creates an empty array with no elements. To create an array with elements, place the elements inside [] and separate them with
commas (,): const arr = [1, 2, 3, 4, 5];
To print an array, simply use console.log():
const arr = [1, 2, 3, 4, 5];

console.log(arr);

Indexes
Each element in an array has a unique index.
Indexes start from 0. The first element has an index of 0, the second element has an index of 1, and so on.
Accessing array data is done by specifying the index in square brackets ( [index]) after the array name: arrayName[index]
const arr = [1, 2, 3, 4, 5];

const thirdElement = arr[2]; // retrieving the 3rd element

console.log(thirdElement);
Arrays can hold different data types, including number, string, boolean, and more.
const arr = [2441.23, "Hello!", false];

console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);

Length Property

The length property is a built-in property of arrays that represents the number of elements in that array. To use this property, use the following syntax:

arrayName.length

const arr1 = [10, 20, 30];


const arr2 = [15, 25, 35, 45, 55];

const x = arr1.length; // x variable represents the arr1 length


const y = arr2.length; // y variable represents the arr2 length

console.log(x);
console.log(y);
Array Methods
Arrays are versatile for storing and retrieving data. Retrieving data using square brackets [] is called indexing.
let arr = [1, 2, 3, 4, 5, 6];
arr[3] // This is indexing
Adding Elements
Push The push() method adds a new value to the end of the array:

let arr = [1, 2, 3];

arr.push(4);
arr.push(5);
arr.push(6);

console.log(arr);
Unshift The unshift() method works like the push() method, but it inserts the value at the beginning of the array.

let arr = [1, 2, 3];


console.log("Array:", arr);

arr.unshift(222); // Insert element at the start

console.log("Array:", arr);
Indexing

let arr = [1, 2];

arr[2] = 3;
arr[3] = 4;

console.log(arr);

Indexing allows you to assign a value to a specified index, reassign a previous value, and more:

let arr = [1, 2, 3];

arr[0] = 4;

console.log("Array:", arr);
To create a new element in the array without mistakes, you can use the push(value) method or the arr[arr.length] = value expression:

let myArray = [];

myArray[myArray.length] = "indexing";
console.log("After first indexing:", myArray);

myArray.push("pushing");
console.log("After first pushing:", myArray);

myArray[myArray.length] = "indexing";
console.log("After second indexing:", myArray);

myArray.push("pushing");
console.log("After second pushing:", myArray);
Deleting Elements
Pop The pop() method deletes the last element in an array and allows you to save it to another variable:
let arr = [11, 22, 33, 44];
console.log("Array:", arr);

let x = arr.pop(); // Remove and save the last element in arr to


variable x

console.log("Popped element:", x);


console.log("Array now:", arr);
Shift The shift() method works like pop(), but it removes the first element from an array:

let arr = [11, 22, 33, 44, 55, 66];


console.log("Array:", arr);

let popped = arr.pop(); // Remove the last element

console.log("Popped:", popped);
console.log("Array:", arr);

let shifted = arr.shift(); // Remove the first element

console.log("Shifted:", shifted);
console.log("Array:", arr);
Basic Operations
Assignment
The assignment is a fundamental operation that assigns values to variables, constants, array elements, and more. This operation is performedusing the = symbol.

let a; // Declare a variable `a`


const b = 26; // Define a constant `b` with the assignment of `26`

a = 15; // Assign the value `15` to the variable `a`

console.log("a =", a, "b =", b);

a = []; // Assign an empty array to the variable `a`

a[0] = 5; // Assign the value `5` to the first element of array `a`

console.log("Array:", a);
Mathematical Operations
JavaScript can perform the following operations with numbers:
•Addition (+);
•Subtraction (-);
•Multiplication (*);
•Division (/);
•Remainder, or Modulo (%);
•Exponent (**).

Addition and Subtraction Multiplication and Division


console.log(12 * 3); // Multiplication
console.log(25 + 13); // Addition console.log(12 / 3); // Division
console.log(37 - 2); // Subtraction console.log(273 / 23); // Division
let a = 25, b = 23; let a = 77, b = 11;
console.log(a + b); // Addition console.log(a * b); // Multiplication
console.log(a - b); // Subtraction console.log(a / b); // Division
Remainder (Modulo) Exponent
This operation returns the remainder of a division and is performed using the % operator: This operation raises a number to a certain power. The first number
is the base, and the second is the exponent to which it must be raised.
console.log(77 % 10); It is performed using the ** operator:
console.log(25 % 11); console.log(10 ** 6); // 10 * 10 * 10 * 10 * 10 * 10 (6 times)
console.log(2 ** 7); // 2 * 2 * 2 * 2 * 2 * 2 * 2 (7 times)
let a = 27, b = 21;
console.log(a % b); let a = 2;
let b = 3;
console.log(a ** b);
Operations with Assignment
JavaScript provides several assignment operators:
•Addition Assignment (+=);
•Subtraction Assignment (-=);
•Multiplication Assignment (*=);
•Division Assignment (/=);
•Remainder (Modulo) Assignment (%=);
•Exponentiation Assignment (**=).

let a = 17;
let a = 17; a = a + 5;
a += 5; This code is equivalent to the following: console.log(a);
console.log(a);

The expression a += 5 accomplishes the same as a = a + 5.


Increment and Decrement
Increment and Decrement are operations used to increase or decrease a variable's value by 1.

Increment Decrement
The increment operation is performed using the ++ operator: The decrement operation is performed using the -- operator:

let a = 0; let a = 5;
a++; a--;
console.log(a); console.log(a);
a++; a--;
console.log(a); console.log(a);
a++; a--;
console.log(a); console.log(a);

The expression a++ is equivalent to a = a + 1 or a += 1. The expression a-- is equivalent to a = a - 1 or a -= 1.


Comparison Operations These operations return a boolean value (true or false).
JavaScript offers several comparison operators for comparing
values: Strict comparison
•Equal to (==);
Strict comparison checks the types of values and values. The Strict Equal To (===) operator returns true -
•Strict Equal To (===); if both the values and their types are the same, while !== returns true if they are different.
•Not Equal To (!=);
•Strict Not Equal To (!==); console.log("5 === 5 is", 5 === 5);
•Greater Than (>);
console.log("5 === '5' is", 5 === '5');
•Greater Than or Equal To (>=);
•Less Than (<); console.log("5 == '5' is", 5 == '5');
•Less Than or Equal To (<=).
console.log("5 !== 5 is", 5 !== 5);
Equal and Not Equal
console.log("5 !== '5' is", 5 !== '5');
The Equal To operation (==) returns true if the first value equals the second value and false otherwise.
Conversely, the Not Equal To operation (!=) returns true if the values are unequal. console.log("5 != '5' is", 5 != '5');
console.log("Equal to:");
console.log("5 == 5 is", 5 == 5); console.log("Type of 5 is", typeof(5));
console.log("5 == 4 is", 5 == 4); console.log("Type of '5' is", typeof('5'));
console.log("5 == 4.99 is", 5 == 4.99);

console.log("Not equal to:");


console.log("5 != 5 is", 5 != 5);
console.log("5 != 4 is", 5 != 4);
console.log("5 != 4.99 is", 5 != 4.99);

The = operator is for assignment, while == is for comparison. Be careful to distinguish them.
Greater and Less
The Greater Than (>) operator returns true if the first value exceeds the second. Conversely, the Less Than (<) operator returns true if the first value is less than the second.

console.log("5 > 5 is", 5 > 5);


console.log("5 > 4.99 is", 5 > 4.99);
console.log("5 > 5.0000001 is", 5 > 5.0000001);

console.log("5 < 5 is", 5 < 5);


console.log("5 < 4.99 is", 5 < 4.99);
console.log("5 < 5.0000001 is", 5 < 5.0000001);

Greater/Less Than or Equal to


console.log("5 >= 5 is", 5 >= 5);
console.log("5 >= 4.99 is", 5 >= 4.99);
console.log("5 >= 5.0000001 is", 5 >= 5.0000001);

console.log("5 <= 5 is", 5 <= 5);


console.log("5 <= 4.99 is", 5 <= 4.99);
console.log("5 <= 5.0000001 is", 5 <= 5.0000001);

The >= operator combines > and ==, not ===. The <= operator works similarly.
Logical Operations
There are three logical operators in JavaScript:
•AND (&&);
•OR (||);
•NOT (!).

AND (&&)
The AND (&&) logical operator returns true only when both values it operates on are true. The result is false if any value is false.

console.log(true && true);


console.log(true && false);
console.log(false && true);
console.log(false && false); NOT (!)
The NOT (!) operator inverts the boolean value. It turns true into false and false into true.
OR (||)
console.log(true || true); console.log(!true);
console.log(true || false); console.log(!false);
console.log(false || true);
console.log(false || false);
Using Logical Operators
let a = 5, b = 3;

console.log(a > 4 && b > 4);


console.log(a > 1 && b > 1);
String Concatenation

Concatenation is the process of combining two strings. This operation is achieved using the + operator:

let wordOne = "Hello";


let wordTwo = "World";

console.log(wordOne + wordTwo);
String concatenation does not automatically add spaces. You need to manually include spaces like string1 + " " + string2.

let wordOne = "Hello";


let wordTwo = "World";

console.log(wordOne + ", " + wordTwo + "!");

The += operator allows you to add text to a string-type variable:


Concatenation with Assignment

let text = "Were";


text += "wolf";
text += "!";

console.log(text)
Conditional Statements

if Statements
The if keyword allows you to open a code block that will be executed if the given condition is true:

if (true) {
console.log("It's TRUE!");
}

if (false) {
console.log("It's FALSE!");
}
The syntax of an if statement is straightforward: it begins with the if keyword, followed by the condition enclosed in parentheses (), and a code block enclosed in curly
braces {}.

if (condition) {
// Code block
}
An expression, as well as a value, can be considered as a condition.
In the example, when a = 935, there are four conditions:
let a = 935;

if (a > 17) {
console.log("The variable is greater than 17");
}

if (a > 235124) {
console.log("The variable is greater than 235124");
}

if (a > 0) {
console.log("The variable is greater than 0");
}

if (a < 0) {
console.log("The variable is less than 0");
}
let a = 5;
let b = 3;
let c;

if (a > 0 && b > 0) {


c = a - b;
console.log("c =", c);
}

if (a > 2 && b > 2) {


c = a + b;
console.log("c =", c);
}

console.log(a, b, c);
else
In the example, the condition a >= 100 evaluates to false, so the code block within the if statement is
let a = 60; not executed. Instead, the code block within the else statement is executed because the if condition
is false.

if (a >= 100) {
console.log("a is greater than or equal to 100");
} else {
console.log("a is less than 100");
}

The syntax of the else statement is similar to that of the if statement, except it doesn't require a condition or parentheses ().

When using an else statement, do not place the end-of-command (;) after the if code block ({}), as this will result in a SyntaxError. The if-else statement is
considered a single command.
else if The else if construct provides a solution for selecting a specific code block within a series of conditions:
let a = 11; if (condition) {
// Code block
if (a > 15) { } else if (condition) {
console.log('greater than 15'); // Repeat the `if` syntax
} }
Let's apply this to our example:
if (a > 10) {
let a = 11;
console.log('greater than 10');
}
if (a > 15) {
console.log("greater than 15");
if (a > 5) {
} else if (a > 10) {
console.log('greater than 5');
console.log("greater than 10");
}
} else if (a > 5) {
console.log("greater than 5");
if (a > 0) {
} else if (a > 0) {
console.log('greater than 0');
console.log("greater than 0");
}
}
Now, we've created a sequence of conditions. When at least one if condition becomes true, the chain is interrupted.

This structure is useful when you only need one condition to be satisfied.
Adding else

let a = -61;

if (a > 15) {
console.log("greater than 15");
} else if (a > 10) {
console.log("greater than 10");
} else if (a > 5) {
console.log("greater than 5");
} else if (a > 0) {
console.log("greater than 0");
} else {
console.log("No condition is satisfied");
}

You might also like