0% found this document useful (0 votes)
6 views27 pages

2

Uploaded by

j5cw7k6222
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
6 views27 pages

2

Uploaded by

j5cw7k6222
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 27

Chapter 2

Values, Types, Variables, and


Operators

1
Objectives
 Learn the core data types in JavaScript and their
practical usage.
 Declare variables using the let, const, and var
keywords and explain the differences between them
 Initialize variables with appropriate values of different
data types.
 Use the typeof operator to determine the data type of
a given value.
 Utilize arithmetic operators (+, -, *, /, %) to perform
mathematical calculations.
 Apply comparison operators (==, !=, ===, !==, <, >,
<=, >=) to compare values and make logical decisions.
Data Types
 Primitive Data Types
• Numbers
• Strings
• Boolean(True, False)
• Undefined
• Null
• Symbol(ES6 or later)
 Non Primitive Data Types
• Objects
• Arrays
• Date
Number
Represents numeric values, including both integers and floating-point numbers.
For example:
let age = 30;
let price = 19.99;

Strings
Represents text or sequences of characters enclosed in single (' ') or double (" ")
quotes. For example :
let name = “Mohamed";
let message = 'Hello, World!';
Boolean
Represents a binary value, which can be either true or false. Booleans are often
used for making decisions and comparisons. For example:
let isVisible = true;
let isLoggedIn = false;

Undefined
A special value assigned to variables that have been declared but not yet
assigned a value. For example:
let undefinedVar;
console.log(undefinedVar); // Outputs: undefined
Null
Represents the intentional absence of any object value. It's often used to signify
that a variable has no value or that an object property doesn't exist.
For example:
let emptyValue = null;

Symbol
Symbols are unique and immutable values often used as property keys in
objects to prevent unintentional property name collisions :
Variables
Variables are used to store and manage data in JavaScript. You can declare
variables using the let, const, or var keywords.
JavaScript Variables can be declared in 4 ways:
• Automatically
x = 10;
• Declaring a variable using let
let x = 10;
• Declaring a constant variable using const
const PI = 3.14;
• Declaring a variable using var (less recommended)
var y = "Hello";
Cont…

• let: Allows you to change the value of the variable.


• const: Declares a constant variable whose value cannot be changed once
assigned.
• var: Older way to declare variables; it has some scoping quirks and is less
recommended in modern JavaScript.
Primitive Data Types vs Composite
Data Types
• Variables for primitive data types hold the actual value of the
data
• Variables for composite types hold only references to the
values of the composite type
Note: We say variables contain values. This is an important
distinction to make. Variables aren't the values themselves; they
are containers for values. You can think of them being like little
cardboard boxes in which you can store things.

9
Cont…
In JavaScript, variable names (also known as identifiers) must follow specific
rules to be valid. These rules help maintain consistency and readability in your
code. Here are the key rules for naming variables in JavaScript
 Variable Names Must Start with a Letter, Underscore (_), or Dollar Sign ($).
 Subsequent Characters Can Include Letters, Digits, Underscores, and Dollar
Signs.
 Variable Names Are Case-Sensitive.
 Reserved Words Are Not Allowed.
 Use Descriptive and Meaningful Names.
Programming
Tips
□ It is a good idea to end □ Recommended: a = 3;
each program statement b = 4;
□ Acceptable:
with a semi-colon;
a = 3; b = 4;
Although this is not
necessary, it will prevent
coding errors
The full list of keywords and
reserved words
break ,case ,catch ,class ,const ,continue ,debugger, default,
delete, do ,else ,enum ,export ,extends ,false,
finally ,for ,function ,if, implements, import, interface,
in ,instanceof ,let ,new ,package ,private ,protected, public,
return ,static, super, ,switch, this, throw, true, try ,typeof ,var,
void ,while ,with , yield.

12
JavaScript Comments

• JavaScript comments are hints that a programmer can


add to make their code easier to read and understand.
They are completely ignored by JavaScript engines.
• There are two ways to add comments to code:
// A single line comment

/* It is a multi-line comment.
It will not be displayed upon
execution of this code */
13
Operators
symbols that perform operations on values.
JavaScript includes various types of operators:
Arithmetic Operators
Operator Description

+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement

Example:
let result = 5 + 3;
console.log(result) // result is 8
Cont…
Comparison Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

Example:
let isEqual = 2 === 3;
console.log(isEqual) // isEqual is false
Cont…
Logical Operators
Operator Description

&& logical and


|| logical or
! logical not

Example:
let isTrue = true && false;
console.log(isTrue) // false

let isTrue = true || false; let isTrue = !true;


console.log(isTrue) // true console.log(isTrue) // false
Cont…
Assignment Operators
Operator Example Same As

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

**= x **= y x = x ** y

Example:
let count = 10;
count += 5; // count is now 15
Cont…
Other Operators
?: Conditional (ternary) operator
Example:
let age = 20;
let message = age > 18 ? "Adult" : “Junior";
Console.log(message) // Adult
Cont…
JavaScript provides two unary operators, the increment (++) operator and the
decrement (--) operator, which are used to increase or decrease the value of a
variable by 1, respectively. These operators can be applied to variables that hold
numeric values.
Increment Operator (++):
•The increment operator (++) increases the value of a variable by 1.
•It can be used both as a postfix operator (e.g., x++) or as a prefix operator (e.g.,
++x).
Postfix Example:
let x = 5;
let y = x++; // y will be 5, and x will be 6
Prefix Example:
let x = 10;
let y = ++x; // y will be 11, and x will be 11
Cont…
Decrement Operator (--):
•The decrement operator (--) decreases the value of a variable by 1.
•Like the increment operator, it can also be used as a postfix operator (e.g., x--)
or as a prefix operator (e.g., --x).
Postfix Example:
let x = 8;
let y = x--; // y will be 8, and x will be 7
Prefix Example:
let x = 15;
let y = --x; // y will be 14, and x will be 14
Cont…
Not all operators are symbols. Some are written as words. One
example is the typeof operator, which produces a string value naming
the type of the value you give it.
console.log(typeof 4.5)
// number
console.log(typeof “x”)
// string

21
Cont…
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"

22
Automatic/Implicit type conversion
JavaScript employs automatic type conversion, also known as type coercion, to
convert values from one data type to another in certain situations. This can
happen implicitly without the need for explicit type conversion functions or
operations. Understanding how automatic type conversion works is essential
for writing robust JavaScript code. Here are some common scenarios of
automatic type conversion:
String Concatenation implicit conversion
let age = 25;
let message = "I am " + age + " years old."; // Implicitly converts age to a string
Numeric Operations implicit conversion
let numStr = "42";
let result = numStr * 2; // Implicitly converts numStr to a number: result is 84
23
Cont…
Comparison Operators implicit conversion
let num = 10;
let strNum = "5";
console.log(num > strNum);
// Implicitly converts strNum to a number for comparison: true

24
A table listing some commonly used JavaScript built-in functions and methods, including
their descriptions:

Function/Method Description
Displays a dialog box with a specified
alert(message) message.
Displays a dialog box with a prompt for
prompt(message) user input.
Displays a dialog box with a
confirm(message) confirmation message.
Outputs data to the browser's console
console.log(data) for debugging.
Writes HTML content directly to the
document.write(text) document.
25
Escape character
Escape Sequence Character Represented Description

\\n Newline Inserts a newline character.

\\t Tab Inserts a tab character.

\' Single Quote Escapes a single quote within a string.

\" Double Quote Escapes a double quote within a string.

\\ Backslash Escapes a backslash within a string.

26
END

27

You might also like