JavaScript
The Game
Course Prerequisites
HTML CSS
Course Objectives
Learn about JavaScript, Learn how to build dynamic and Make you fall in love with
its uses and really understand it. interactive websites. JavaScript
Netscape wanted to make making a scripting Netscape hired Brendan Eich
the web more Dynamic language for that reason
Defend Idea by do a
prototype
JavaScript History
Eich do a prototype in
10 days
And finally be JavaScript Second name JavaScript first name
JavaScript was LiveScript was mocha
Fact #1
“
There are two types of people, One who writes it “Java Script” and the other
who writes it “JavaScript”. First one has no idea about what JavaScript is.
”
le vel
1
JavaScript Language Core
Hello Word!
http://www.example.com
Hello World
document.write(‘Hello World’)
Hello World
console.log(‘Hello World’) ok cancel
alert(‘Hello World’)
console
> ‘Hello World’
Intro
Where To ?
<html>
<head> alert(‘hello world’);
<script>
alert(‘hello world’); alert(‘hello world’);
</script>
<script src=“myscript.js”></script>
</head>
<body>
<p>Hello</p>
<script>
alert(‘hello world’);
</script>
<script src=“script.js”></script>
</body>
<html>
index.html script.js
Intro
JavaScript Syntax
- JavaScript is case sensitive Var is not equal to var
- JavaScript statements are separated by semicolons (;).
- Variable Names follows this rules:
- the first character must be a letter, an underscore (_), or a dollar sign ($).
$dollar (√ ) _underScore (√ ) name (√ ) 12twelve (x)
- Subsequent characters may be letters, digits, underscores, or dollar signs.
$do22ar twelve12
Intro
Declaring Variables
var name;
var name, age, email;
var name, age=12;
Intro
Data Types
Intro
String
Primary
Number Data Types
Boolean
Composite
Object
Data Types
Null
Special
Data Types
Undefined
Data Types
Primary Data Types
String Number Boolean
Any character array or Any Numeric value but Has only two values true
text quoted not quoted or false
var str1=“hello JS”; var num1= 8; var isBool= true;
var str2=’11.26’; var num2= 11.26; var isStr= false;
var str3=’false’;
Data Types
Special Data Types
null undefined
This describes the no valid value , The undefined value is returned when you
And has only one value null declare a variable that has never had a
value assigned to it.
var thisIsNull = null; var num1; //num1 is undefined
Data Types
JavaScript is Dynamic
var var1; //its type is undefined
var1 =“ahmed”; //Now, its type is string
var1 =12; //Now, its type is number
var1 = true; //Now, its type is boolean
Data Types
Checking variables data types
typeof variable_name
var name;
typeof name;
//undefined
name =“ahmed”;
typeof name;
//string
name = null;
typeof name;
//object How??
typeof name == ‘object’;
//true
Data Types
Operators
Arithmetic Operators
Operator Example Same As
= x = x = y
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
Operators
+ operator
String input output
+ (concatenation)
“ITI” + “ OS” ITI OS
Number
20 + “17” 2017
+ (arithmetic)
“is Exist ” + true is Exist true
Boolean “not ” + undefined Not undefined
+ (arithmetic) 37 + null 37
undefined 37 + undefined NaN
true + false 1
+ (arithmetic)
true + undefined NaN
null
Operators
Comparison Operators
a <op> b
Operator Description
== Return true if value of a equal to value of b.
=== Return true if value and type of a equal to value and type of b.
!= Return true if value of a not equal to value of b.
!== Return true if value and type of a not equal to value and type of b.
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Operators
Fight No#1
== ===
It compares only the variable value It compares the variable type and value
== Operator boolean number string any
1| == ===
2| == Number( ) === Number( )
null
3| == or
undefined
false
4| null == undefined true
input output input output
“20” == 20 true true == 1 true
0 == null false true == 4 false
“true” == true false false == 0 true
NaN == NaN false NaN == undefined false
undefined == null true
Operators
Logical Operators
&& and Gate
|| or Gate
! not Gate
input output
(0 == null) && (true == 1) false
(0 == “”) || (“2” == 2) true
!(null == undefined) false
Operators
&& Operator
&& operator seeks for falsy value and return the first truthy value it find or the last value it stops at
input output
true && 4 4
0 && true 0
1 && 2 2
‘Ahmed’ && ‘’ ‘’
false && null false
Operators
|| Operator
|| operator seeks for truthy value and return the first truthy value it find or last value it stops at
input output
true || 4 true
0 || true true
1 || 2 1
‘Ahmed’ || ‘’ ‘Ahmed’
false || null null
Operators
Control Flow
If statement
if Condition 1 Commands 1
else if Condition 2 Commands 2
else if Condition n Commands n
else Default Default Commands
Control Flow
Falsy Values
if (name) {
alert(“hi”);
}else{
alert(“Bye”);
}
If name has falsy value it will execute the code in the Else statement
So what is the falsy values :
0 , false, null ,undefined, “”, NaN
Control Flow
switch . . . case
switch (typeof typedVar) { boolean number string default
case ‘boolean’:
console.log(‘blue’)
break
case ‘number’:
console.log(‘green’)
break var typedVar = 3
case ‘string’:
console.log(‘red’)
break
default:
console.log(‘grey’) > green
break > red
} > grey
Control Flow
while Loop
Condition:
while (Green === true && Red === false)
Command:
Car.move();
}
Control Flow
for Loop
for(var i=0;i<5;i++){
Bottle.fill(cup,water);
5
i = 45
12
03 <=5
For loop will finish
executing here
Control Flow
Fight No#2
continue break
It makes program skip the current iteration of It makes program exit loop without
loop without completing it completing the remaining iterations
Dialogs
Alert Dialog
alert(text);
Return : Doesn’t Return any value
alert(“Hello JavaScript!”);
OR
var greetings = “Hello JavaScript!”;
alert(greetings);
Dialogs
Prompt Dialog
prompt(text, default return value);
Return : String
var person = prompt("Please enter your name", “Ahmed");
console.log(person) //person = Ahmed
Dialogs
Confirm Dialog
confirm(message)
Return : Boolean
var isReady = confirm(“Are you ready?");
if(isReady){
alert(“Yes”);
}else{
alert(“No”);
}
Dialogs
Functions
Intro
Function
name Parameters Commands Return Values
function name(parameter1, parameter2, parameter3)
{
code to be executed
return true;
}
Functions
Intro
Function
name Parameters Commands Return Values
function multiply(num1,num2) {
var result = num1 * num2;
return result;
}
Calling it:
var result = multiply(3,4);
alert(result); // result = 12
Functions
Scope
Global Scope
var globalVar = 0;
function1 function2
{ {
var funcOneVar = 1; var funcTwoVar = 4;
globalVar++; globalVar++;
console.log(globalVar); console.log(funcTwoVar);
console.log(funcTwoVar); console.log(funcOneVar);
} }
Result
function1(); 1
undefined
function2();
4
console.log(globalVar); undefined
2
console.log(funcOneVar);
undefined
Functions
Objects
Everything in JavaScript is an Object
Intro
It has characteristics
Properties
Bike.color
Bike.height
Bike.width
Bike.weight
Bike.move()
Bike.stop()
Bike.brake()
Bike.jump()
Bike is an Object Methods
It does some actions
Objects
Literal Object
{
name: ‘ali’,
age: 19,
isEgyptian: true
}
‘name’ : “ali”
Keys ‘age’ : 19 Values
‘isEgyptian’ : true
That’s Enough for now !
Objects
Built-in Objects
overview
They are helper objects that wrap some methods and properties about something like Date,
Mathematical Operations , etc.
Built-in Object
Object Methods and Built-in Additional Object
Properties Methods and Properties
Built-in Objects
Strings
var message = “this is string”
input output
message.toUpperCase() THIS IS STRING
message.slice(5,7) is
message.replace(“is”, “was”) thwas is string
message.charAt(2) i
message.indexOf(“is”) 2
message.lastIndexOf(“is”) 5
Built-in Objects
Numbers
var num = 15.528
input output
num.toString() “15.528”
num.toFixed(2) “15.53”
num.toPrecision(3) “15.5”
num.toPrecision(2) “16”
parseInt(num) 15
Built-in Objects
Arrays
Arrays are a special kind of objects, with numbered indexes
Built-in Objects
overview
var myArr = [“string”, 11, true, null];
‘0’ : “string”
‘1’ : 11
Keys(Indices) Values
‘2’ : true
‘3’ : null
Length: 4
Object
myArr[50] = “no50”;
‘50’ : “no50” Length: 51
Arrays
Methods
var myArr = [“C”, “JavaScript”, “Python”, “Java”, “php”];
myArr input output
C++
C myArr.pop() php
JavaScript myArr.push(“go”) 4
Python myArr.shift() C
Java myArr.unshift(“C++”) 0
go
Scala
php myArr.splice(4,0,“Scala”) []
delete myArr[3] true
Arrays
Math
The Math object allows you to perform mathematical tasks
input output
Math.PI 3.14
Math.sqrt(25) 5
Math.abs(-1) 1
Math.floor(1.6) 1
Math.ceil(1.4) 2
Math.round(1.5) 2
Built-in Objects
Date
var d = new Date()
MISSION #1
Try
exploring its Methods and Properties
Built-in Objects
Tips and Tricks
for … in
for…in used to loop into object by iterating its keys
var obj = {
name: ‘Ahmed’,
age: 19
}
var info = ‘’
for (var k in obj) {
info += ‘My ’ + k + ‘ is ’ + obj[k] + ‘ ’
}
// info = ‘My name is Ahmed My age is 19 ’
Tips and Tricks
? operator
condition ? success_expression : fail_expression
var canFly = true
var bird = canFly ? ‘Dove’ : ‘Penguin’
// bird is Dove
Tips and Tricks
Challenges
Rules
1 If you have Syntax Error, Solve it yourself. You are able to do that.
2 Mentors exist to guide you to the best way to solve the problem and why errors raised
not to solve the problem or trace your code to solve syntax errors.
3 Steps of Solving the problem:
-Think.
-Think again.
-Use Pen and Papers to convert your thoughts into Procedures.
-Convert your previous pseudo code into JavaScript Code using
its syntax rules.
-Don’t be afraid of syntax errors. It is easy to solve. Read it clearly
and you will solve it.
- Check the output of every step you do and then check them all.
4 The most important rule is to enjoy challenging yourself and don’t stress your mind by the
headache of assignments delivery’s deadlines.
Lab 1
Beginner
Fizz Buzz Game
Write a function that take a number ad check if the given number is divided by 3 only, 5 only or both
and print the suitable sentence. Follow the below Rule.
Number Sentence
Input Output
15 “fizz buzz”
Rule :
Notes divided by 3 only =“fizz”, divided by 5 only =“buzz”, divided by 3 & 5= “fizz buzz” ,
Neither divided by 3 nor 5 = “none”
Lab
Beginner
Bottle Game
Write a function that take an array of persons’ names and return two random names of them.
array
Input [“ahmed”, “islam”, “sandra”, “Fatma”, “Ali”]
array
Output [“sandra”, “Ali”]
Lab
Intermediate
Character Game
Write a function that take a sentence and a letter to search for it in the given sentence and return its
locations in that sentence.
String Letter
Input “This is javaScript” “i”
array
Output [2, 5, 15]
Lab
Advanced
Greedy Game
Write a function that take a number and follow the below rule to convert it into dollars, quarters, dime,
nickels and cents.
Number
Input 15.92
Sentence
Output You have 15 dollar, 3 quarter, 1 dime, 1 nickel and 2 cent
Rule :
Notes 1 dollar = 100 cent, 1 quarter = 25 cent, 1 dime = 10 cent, 1 nickel = 5 cent
Lab
Bonus
Mario Game
Sentence
*
Number **
Input 5 Output ***
****
*****
Lab
Bonus
Who Am I Game
Do you fly?
Yes No
Are You Wild? Do you live under sea?
Yes No Yes No
And
Where
am I ? Are You Wild? Are You Wild?
Yes No Yes No
Eagle Parrot
Shark Dolphin Cat
Lab