Introduction To Javascript
Introduction To Javascript
Introduction To Javascript
Topics
Introduction to Javascript
What is JavaScript?
JavaScript is a scripting or programming language that allows you to
implement complex features on web pages
What is JavaScript?
The core JavaScript language defines a minimal API for working with numbers,
text, arrays, sets, maps, and so on, but does not include any input or output
functionality
Input and output (as well as more sophisticated features, such as networking,
storage, and graphics) are the responsibility of the “host environment” within
which JavaScript is embedded
What is JavaScript?
The ECMA-262 specification contains detailed and formalized information
about JavaScript. It defines the language
https://www.ecma-international.org/publications/standards/Ecma-262.htm
Where JavaScript run
JavaScript can execute
in the browser
on the server
on any device that has a special program called the JavaScript engine
Javascript Engine
The browser has an embedded engine sometimes called a “JavaScript virtual
machine”
Example Engines
SpiderMonkey – in Firefox
“Chakra” for IE
TypeScript adds strict data typing to simplify the development and support of
complex systems. It is developed by Microsoft
VS Code
Browser
Developer Console
Ctrl + Shift + J
Getting Started
Create index.html file
alert(‘Hello World’);
Ways to Use Javascript
On your web browser press F12 to open a developer tool and then select the
Console tab
Ways to Use Javascript
<html lang="en">
Create an HTML file and use the
<script> tag in the <head> or <head>
<body> tag to put your Javascript <meta charset="UTF-8" />
code <title>Document</title>
<script>
console.log("Hello World");
</script>
</head>
<body></body>
</html>
Ways to Use Javascript
<html lang="en">
Create an HTML file and use the <head>
<script> tag in the <head> or <meta charset="UTF-8" />
<body> tag to put your Javascript
<title>Document</title>
code
</head>
<body>
<script>
console.log("Hello World");
</script>
</body>
</html>
Ways to Use Javascript
Use separate javascript file with <html lang="en">
file extension of .js and attach <head>
the Javascript file to the HTML <meta charset="UTF-8" />
file as shown <title>Document</title>
</head>
<body>
<script src="example.js">
</script>
</body>
</html>
Exercise
Using external .js file create a program which print “Hello World” on the
Console window
Statements
Statements are syntax constructs and commands that perform actions.
alert('Hello');
alert('World');
Comments
One-line comments //
Multiline comments /* */
/*
Hello world alert statement
*/
alert('Hello');
Variables
To create a variable use the let keyword
alert(message); // Hello!
Variable naming
The name must contain only letters, digits, or the symbols $ and _
let 1a;
let my-name;
Variable naming
What is wrong with the following variable names
alert(መልእክት);
Constants
To declare a constants use const
null for unknown values – a standalone type that has a single value null
let n = 123;
n = 12.345;
Besides regular numbers, there are so-called “special numeric values” which
also belong to this data type: Infinity, -Infinity and NaN
BigInt
In JavaScript, the “number” type cannot represent integer values larger than
(253-1) (that’s 9007199254740991), or less than -(253-1) for negatives
Backticks: `Hello`
let age;
As an operator: typeof x
As a function: typeof(x)
The typeof operator
typeof undefined // "undefined"
typeof 0 // "number"
alert("Hello");
Interaction: alert, prompt, confirm
prompt
The function prompt accepts two arguments, the syntax is shown below
default An optional second parameter, the initial value for the input
field
Interaction: alert, prompt, confirm
prompt
alert(`You are ${age} years old!`); // You are 100 years old!
Interaction: alert, prompt, confirm
confirm
The function confirm shows a modal window with a question and two
buttons: OK and Cancel
result = confirm(question);
Interaction: alert, prompt, confirm
confirm
There are also cases when we need to explicitly convert a value to the
expected type
String Conversion
String conversion happens when we need the string form of a value
Values Becomes
undefined NaN
null 0
true and false 1 and 0
string Whitespaces from the start and end are removed. If the
remaining string is empty, the result is 0. Otherwise, the
number is “read” from the string. An error gives NaN
Numeric Conversion
Addition + Division /
Subtraction - Remainder %
Multiplication * Exponentiation **
String concatenation with binary +
If the binary + is applied to strings, it merges (concatenates) them
The unary plus or, in other words, the plus operator + applied to a single
value, doesn’t do anything to numbers
But if the operand is not a number, the unary plus converts it into a number
Numeric conversion, unary +
// No effect on numbers
let x = 1;
alert( +x ); // 1
let y = -2;
alert( +y ); // -2
// Converts non-numbers
alert( +true ); // 1
alert( +"" ); // 0
Increment/Decrement
Increment ++ increases a variable by 1
let counter = 2;
counter++; // same as counter = counter + 1
alert( counter ); // 3
Increment/Decrement
Decrement -- increases a variable by 1
let counter = 2;
counter--; // same as counter = counter - 1
alert( counter ); // 1
Exercise
What are the final values of all variables a, b, c and d
let a = 1, b = 1;
let c = ++a; // ?
let d = b++; // ?
Exercise
What are the values of a and x?
let a = 2;
let x = 1 + (a *= 2);
Exercise
What are results of these expressions?
"" + 1 + 0 "4" - 2
"" - 1 + 0 "4px" - 2
true + false " -9 " + 5
6 / "3" " -9 " - 5
"2" * "3" null + 1
4 + 5 + "px" undefined + 1
"$" + 4 + 5 " \t \n" - 2
Exercise
The output in the example below is 12 (for default prompt values)
Why?
How do you fix it
alert(a + b); // 12
Comparisons
Greater/less than: a > b, a < b
Equals: a == b
Comparisons
alert( 2 > 1 ); // true (correct)
alert( 2 == 1 ); // false (wrong)
alert( 2 != 1 ); // true (correct)
A strict equality operator === checks the equality without type conversion.
Strict equality
5 > 4
"apple" > "pineapple"
"2" > "12"
undefined == null
undefined === null
null == "\n0\n"
null === +"\n0\n"
The “if” statement
let year = prompt('In which year was ECMAScript-2015
specification published?', '');
if (year == 2015) {
alert("You guessed it right!");
} else {
alert("How can you be so wrong?"); // any value except 2015
}
Several conditions: “else if”
let year = prompt('In which year was ECMAScript-2015
specification published?', '');
if ("0") {
alert("Hello");
}
Exercise
Convert the following conditional flow chart into if … else construct and
ternary operator
Exercise
Using if..else, write the code which gets a number via prompt and then
shows in alert:
0, if equals zero.
Exercise
Rewrite the following if...else using the conditional operator ?...:
let result;
if (a + b < 4) {
result = "Below";
} else {
result = "Over";
}
Logical Operators
There are four logical operators
|| (OR),
&& (AND),
! (NOT),
?? (Nullish Coalescing).
|| (OR)
alert(true || true); // true
alert(false || true); // true
alert(true || false); // true
alert(false || false); // false
OR "||" finds the first truthy value
The OR || operator does the following:
For each operand, converts it to boolean. If the result is true, stops and
returns the original value of that operand
If all operands have been evaluated (i.e. all were false), returns the last
operand
If all operands have been evaluated (i.e. all were truthy), returns the last
operand
AND “&&” finds the first falsy value
// if the first operand is truthy,
// AND returns the second operand:
alert( 1 && 0 ); // 0
alert( 1 && 5 ); // 5
if a is defined, then a
let i = 0;
while (i < 3) { // shows 0, then 1, then 2
alert( i );
i++;
}
The “do…while” loop
do {
// loop body
} while (condition);
let i = 0;
do {
alert( i );
i++;
} while (i < 3);
The “for” loop
for (begin; condition; step) {
// ... loop body ...
}
let i = 0;
for (;;) {
// repeats without limits
}
Breaking the loop
Normally, a loop exits when its condition becomes falsy
But we can force the exit at any time using the special break directive
let sum = 0;
while (true) {
let value = +prompt("Enter a number", '');
if (!value) break;
sum += value;
}
alert( 'Sum: ' + sum );
Continue to the next iteration
for (let i = 0; i < 10; i++) {
alert(i); // 1, then 3, 5, 7, 9
}
Exercise
What is the last value alerted by the following code? Why?
let i = 3;
while (i) {
alert( i-- );
}
Exercise
Replace "for" with "while"
Write the code which outputs prime numbers in the interval from 2 to n.
case 'value2':
...
[break]
default:
...
[break]
}
The "switch" statement let a = 2 + 2;
switch (a) {
case 3:
alert( 'Too small' );
break;
case 4:
alert( 'Exactly!' );
break;
case 5:
alert( 'Too big' );
break;
default:
alert( "I don't know such values " );
}
switch (browser) {
Exercise
case 'Edge':
alert( "You've got the Edge! " );
break;
Write the code shown using
if..else case 'Chrome':
case 'Firefox':
case 'Safari':
case 'Opera':
alert( 'Okay we support these browsers too '
);
break;
default:
alert( 'We hope that this page looks ok! ' );
}
Exercise let a = +prompt('a?', '');
if (a == 2 || a == 3) {
alert( '2,3' );
}
Functions
Functions are the main “building blocks” of the program
function showMessage() {
alert( 'Hello everyone!' );
}
Local variables
A variable declared inside a function is only visible inside that function.
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error!
Outer variables
A function can access an outer variable as well, for example:
function showMessage() {
let message = 'Hello, ' + userName;
alert(message);
}
function sum(a, b) {
return a + b;
}
function checkAge(age) {
if (age > 18) {
return true;
} else {
// ...
return confirm('Did parents allow you?');
}
}
Exercise
Write a function min(a,b) which returns the least of two numbers a and b
Exercise
Write a function pow(x,n) that returns x in power n. Or, in other words,
multiplies x by itself n times and returns the result.
Function expressions
function showOk() {
alert( "You agreed." );
}
function showCancel() {
alert( "You canceled the execution." );
}
alert( sum(1, 2) ); // 3
Multiline arrow functions
let sum = (a, b) => {
let result = a + b;
return result; // we need an explicit "return"
};
alert( sum(1, 2) ); // 3
Exercise
function ask(question, yes, no) {
Replace Function Expressions
if (confirm(question)) yes();
shown with arrow functions
else no();
}
ask(
"Do you agree?",
function() { alert("You agreed."); },
function() { alert("You canceled the execution."); }
);
References
The Modern JavaScript Tutorial