Js Programming 07-06-2024
Js Programming 07-06-2024
NITHIN
[email protected]
Hello world
console.log()
Datatypes in JavaScript
• Number (200, 3.14, …)
• String (“Hello world”, “Pentagon Space”, ‘some string’, …)
Eg:
let person="Hege";
let person = "Hege"; (5 marks for good handwriting? I wish)
Keywords
Reserved words
Examples –
var return
let else
const while
if do
switch try
for (end of thinking capacity)
function
JavaScript Values
• Fixed values (Literals) – numbers and strings
• Dynamic values (Variables) – used to store data values
Declaring variables
JS uses the keywords var, let and const to declare variables
(var –> ES5, let & const -> ES6)
(var -> function scoped, let & const -> block scoped
(let -> can be reassigned, const -> cannot be reassigned)
Rules for naming identifiers
What is an identifier?
Constitution of identifiers –
1. Can include uppercase & lowercase letters, digits, (_) and
($) special characters.
2. Cannot begin with a digit.
3. Keywords cannot be used as identifiers
4. Whitespaces cannot be used while naming identifiers
Remarks
Use const if the value of the variable should remain unchanged.
Use let where the value of the variable keeps changing.
Only use var if you must support old browsers.
var, let and const
Additional points
* const must be initialized
* Variables declared using var are hoisted (usage before declaration)
* Prefer const for arrays, objects, functions, etc.
Operators
Arithmetic Operators (+, -, *, /, %, **, ++, --)
Assignment Operators (=, +=, -=, *=, /=, %=, **=)
Comparison Operators (==, ===, !=, !==, >, >=, <, <=, ?:)
Logical Operators (&&, ||, !)
Type Operators (typeof, instanceof)
Bitwise Operators (&, |, ~, <<, >>)
Unary Operators
Binary Operators
Ternary Operators
Operator Precedence
Arrays
Enclosed within square brackets
Separated by commas
Indexes are zero-based (i.e., starting from 0)
Objects
Enclosed within curly braces {}
Separated by commas
Key-value pairs
Eg:
Why functions
Reusability
Reduce in redundant code
Dynamic code (different arguments provide different results)
Objects again
// Create an Object
const person = new Object();
// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
NOTE –
Strings created with single or double quotes works the same.
There is no difference between the two.
More on strings
Templates are not supported in Internet Explorer.
Escape characters:
String methods
.charAt(position)
.at(position)
.slice(start, end) [end index is not included]
.substring(start, end)
.indexOf(charSequence)
.includes(charSequence) [case-sensitive, ES6]
.startsWith(phrase, startPos)
.endsWith(phrase, endPos) [check if first endPos letters have phrase]
.toLowerCase()
.toUpperCase()
.split(separator) [string to array of strings separated by a
separator]