JavaScript Core
JavaScript Core
Resources and content will be references within the lessons particaularly content
from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript
console.log("Hello World")
console.dir(document)
console.table({first:"test",val:9});
console.error("Hello World")
var a = “Hello”;
console.log(a);
More about JavaScript
● Create index.html and app.js file
● Write some code JavaScript
● Run the file in your browser
Alert
The Window.alert() method displays an alert dialog
with the optional specified content and an OK
button.
window.alert("Hello world!");
alert("Hello world!");
window.alert(message);
Code Snippet
var myName = "Laurence";
var myCourse = "JavaScript";
console.log(myName);
alert("welcome");
var myAge = 40;
console.log(myAge);
Try in the console then in the index.html file
Write an alert in your browser.
alert(“hello”);
alert(“hello”);
Message - “hello”
End of statement - ;
TIP: A semicolon is not necessary after a statement if it is written on its own line. But if more than one
statement on a line is desired, then they must be separated by semicolons. It is considered best practice,
however, to always write a semicolon after a statement, even when it is not strictly needed.
Add JavaScript to website html file
Inside html file or linked to script file
<script src=”code.js”></script>
<script>
///
</script>
TIP : Alert stops the code execution, if in top does not output the content until the button is clicked. Place
JavaScript at the bottom so the rest of the code can render.
Run your index.html file in the browser
Getting started with JavaScript is easy: all you need
is a modern Web browser.
Add JavaScript
Comments in Code JavaScript
● How values are used and assigned
● What variables are
● Var
Comments and Whitespace
Comments // for single line
Comments in JavaScript
Create an index.html file run the code , add a js file run the code. Add javascript
to your webpage both in the script tags and as a linked file. Use alert. Create a
welcome message.
Declarations Variables JavaScript
● How values are used and assigned
● What variables are
● var
Why use Variables?
Symbolize the values within your applications
Example
var x = 1;
console.log(x);
x = 2; - update value
console.log(x);
Lesson Challenge
Declare a variable that holds a
welcome message. Change the
welcome message to a NEW message.
Output it in the console.
if(true){
/// Runs this code only if the check comes back as true
}
Code Snippet
var message;
console.log(message);
message = null;
console.log(message);
var myLight = false;
console.log(myLight);
myLight = true;
if (myLight) {
console.log(myLight);
}
var score1, score2, score3, score4;
var a = "Hello”;
var b = 10;
var c = false;
console.log(a);
Variable Types
var - Declares a variable, optionally
initializing it to a value.
‘let’ is similar to var but has scope. Only accessible within the block of code
that it is defined. let restricts access to the variable to the nearest enclosing
block.
Example
-
Code Snippet
let counter1 = 5;
counter1++;
console.log(counter1);
const counter2 = 10;
counter2++;
console.log(counter2);
Lesson Challenge
Declare a variable called message with
let. Check to see if it exists and if it
does update the value. Output the
variable value to the console.
Code Snippet
let message = "Welcome";
console.log(message);
if (message) {
message = "Updated Message";
}
console.log(message);
Data Types Variable setup
● Null
● Undefined
● Declare multiple variables
● CamelCase
● Variable naming rules
Variables declaring null vs undefined
var a; - initialize as undefined
var test;
console.log(test);
Declare multiple variables in one statement
Comma separate to declare multiple variables.
var a,b,c,d;
TIP camelCase
camel case is more readable
Or
var f = Symbol("value"); // represents a unique identifier. = Symbol (new in ECMAScript 2015). A data
type whose instances are unique and immutable.
temp = 10;
temp = String(10);
temp = String([1,2,3,4])
temp = (100).toString();
temp = Number(‘10’);
temp = Number(true);
temp = Number([1,2,3,4]) //NaN not a number
console.log(temp);
type coercion
when the type is converted by JavaScript
let temp;
temp = 10;
temp = temp + 5;
temp = temp + “five”;
console.log(temp);
Fun with Types
“Hello” + “world”
“5” + 5
“10” - 5
let a = "5";
let b = "10";
console.log(a+b);
JavaScript Operators
● How to use operators
● What are the available operators
● Order of Arithmetic operators
Arithmetic operators do the math
Arithmetic operators take numerical values
(either literals or variables) as their operands
and return a single numerical value. The
standard arithmetic operators are addition (+),
subtraction (-), multiplication (*), and division
(/). standard arithmetic operations (+, -, * /),
https://developer.mozilla.org/en-US/docs/Web/
JavaScript/Reference/Operators/Arithmetic_Op
erators
Operator precedence - The order of things
Operator precedence determines the way in
which operators are parsed with respect to each
other.
https://developer.mozilla.org/en-US/docs/Web/J
avaScript/Reference/Operators/Operator_Prece
dence
Modulus
Remainder (%) Binary operator. Returns
the integer remainder of dividing the two
operands. 12 % 5 returns 2.
JavaScript Operators
● Comparison operators
● Assignment operators
Operators with arithmetic and Assignments
Math operators + - * /
Increment ++ --
Assignment operators
= += =+ *= /=
Assignment Operators
Operators can be used to assign values and
perform calculations. An assignment
operator assigns a value to its left operand
based on the value of its right operand.
https://developer.mozilla.org/en-US/docs/We
b/JavaScript/Reference/Operators/Assignme
nt_Operators
Shorthand = += =+ *= /= ++ --
Meaning and shorthand
-= += =+ *= /= ++ --
Assignment Operators multiple variables
You can assign values to
more variables within one
statement.
Lesson Challenge
What will the output of the total be for this code
let firstNum = 5;
let secondNum = 10;
firstNum++;
secondNum--;
let total = firstNum + secondNum;
console.log(total);
total = 500 + 100 / 5 + total;
console.log(total);
false
undefined
null
NaN
True
Has value
1
Lesson Challenge
Check if a number exists and also check if it is
greater than 50. Show a message in the
console.
Lesson Challenge Code
<script>
let checkNum = 5;
if (checkNum) {
console.log("number exists");
}
if (checkNum > 50) {
console.log("Its bigger than 50");
}
console.log(checkNum);
</script>
JavaScript Conditions
● If statement
● else
Comparison Operators
Lesson Challenge
Use prompt to get a number from the user.
if (condition_1) {
statement_1;
} else if (condition_2) {
statement_2;
} else if (condition_n) {
statement_n;
} else {
statement_last;
}
JavaScript Conditions
The if statement executes a
statement if a specified condition
is truthy. If the condition is falsy,
another statement can be
executed.
Lesson Challenge
Check if a number is greater than 10 output
message accordingly.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
Lesson Challenge
Ask the users age via a prompt
https://developer.mozilla.org/en-US
/docs/Web/JavaScript/Reference/St
atements/switch
Switch example
switch (expression) {
case label_1:
statements_1
[break;]
case label_2:
statements_2
[break;]
...
default:
statements_def
[break;]
}
Lesson Challenge
Select a response depending on the name of the
person in a variable called person.
Lesson Challenge Code
<script>
let person = "Laurence";
switch (person) {
case "John":
console.log(person + " is not my friend.");
break;
case "Jane":
console.log(person + " I don't know that person.");
break;
case "Laurence":
console.log(person + " he is the teacher here.");
break;
case "Steve":
console.log(person + " is a good friend.");
break;
default:
console.log("Don't know that person.");
}
</script>
JavaScript Functions
● What are functions and how to use them
● Create functions
Functions
● Functions are blocks of reusable code - a set of
statements that performs a task or calculates a
value.
● One of the fundamental building blocks in
JavaScript.
● To use a function, you must define it somewhere in
the scope from which you wish to call it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript
/Guide/Functions
Functions
function name(parameters) {
// code to be executed
}
Lesson Challenge
#1 Create a function to output a message from a
variable into the console.
function welcome(message) {
counter++;
let temp = counter + " times run";
console.log(message);
console.log(temp);
}
let myNum = 50;
addTen(myNum);
function addTen(num) {
let temp = Number(num);
console.log(temp + 10);
}
JavaScript Functions
● Parameters
● Multiple arguments
● Default argument value
Functions
Function parameters inside the parentheses ()
in the function definition.
function
name(parameter1,parameter2,parameter3) {
// code to be executed
}
Function Default Arguments
console.log(multiplier(num1, num2));
Lesson Challenge Code
<script>
let num1 = 5;
let num2 = 10;
function multiplier(a, b) {
let total = a * b;
return total;
}
console.log(multiplier(num1, num2));
</script>
JavaScript Functions
● Execute from HTML elements
Functions as attributes
onclick="message()" in element
Runs the block of code in the function. There is a much better way to do this
when you use the DOM but for now try this.
Lesson Challenge
Create 3 buttons that will each update a different
global variable. Output the current values of
each variable in the console.
function test(num) {
return num;
// Function expression
return num;
};
What’s the difference, hoisting…..
TIP : function declarations are hoisted to the top of the code by
the browser before any code is executed. If you need to call a
function before it’s declared, then, of course, use function
declarations.
console.log(test1(5));
console.log(test2(5));
Lesson Challenge Code
<script>
var test1 = function (num) {
return num + 5;
};
console.log(test1(5));
console.log(test2(5));
function test2(num) {
return num + 5;
}
</script>
JavaScript Function scope
● Global Scope values
● Local scope
Functions and Scope
Global vs. Local Variables
JavaScript function recursion
● Create a quick loop of content
● Function within itself
Recursion
A function can refer to and call itself.
function loop(x) {
if (x >= 10) return;
console.log(x);
loop(x + 1); // the recursive call
}
loop(0);
Lesson Challenge
Create a function that asks for a guess from the
user. Use the guess value to compare to see if
the user guessed correctly let them know if
correct or incorrect. Call the function again until
the guess is correct.
(function () {
let firstName = "Laurence"; // can't access outside
})();
(function (firstName) {
console.log("My Name is " + firstName);
})("Laurence");
Lesson Challenge
Use an anonymous IIFE to output your name in the
console.
JavaScript new ES6 Arrow format
● How to shorthand functions
Arrow functions
An arrow function expression (previously, and now incorrectly known as fat arrow
function) has a shorter syntax compared to function expressions and lexically
binds the this value. Arrow functions are always anonymous. https://babeljs.io/repl
Arrow functions
1. Declare variable - name of function to invoke it
2. Define body within {}
Default parameters
Lesson Challenge
Convert one of the earlier functions used in the
course to arrow function format.
function tester(){
console.log(test['a'+a]);
a++;
}
Lesson Challenge
Favorite Things Object
}
</script>
JavaScript functions to create Objects
● Functions can be used to construct Objects
Functions to create Objects
function Car(miles,company,color,price){
this.color=color;
this.miles=miles;
this.price=price;
this.company=company;
Array
const lessons = [‘first’,’second’];
Object Literal
const myInfo =
{first:’Laurence’,last:’Svekis’}
console.log(shopping);
theList[3];
arrayName[indexValue];
Lesson Challenge
Create an array with different data types, return
the values of those data types.
</script>
JavaScript Array are Powerful
● Array memory reference
● Array Length
● Check if its an array
● Get indexOf array item
● Add and remove items from array Methods
● Splice remove from array at index value
Arrays and Array methods
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Gl
obal_Objects/Array
Lesson Challenge
Update your array using various methods
Transform the array below.
into
theList.length;
Array.isArray(theList);
theList[1] = "hello World";
theList.indexOf('Laurence');
theList.push("new one push");
theList.pop();
theList.shift();
theList.unshift("make me first");
theList.splice(1, 2);
JavaScript Arrays even more
● Sort arrays
● Reverse arrays
● Concat array together
● Find in array
● indexOf
Array Methods
https://developer.mozilla.org/en-US/docs/W
eb/JavaScript/Reference/Global_Objects/A
rray
Code Snippet
const myArray = ["a", "hello", 4, 8, 2, "world", "javascript", "course", 99, 1];
const myArray2 = [5, 12, 8, 130, 44];
console.log(myArray);
myArray.sort();
console.log(myArray);
myArray.reverse();
console.log(myArray);
console.log(myArray.indexOf(50));
if (myArray.indexOf(50) === -1) {
console.log("not found");
}
let newArray = myArray.concat(myArray2);
console.log(newArray);
let found = myArray2.find(function (element) {
return element > 10;
});
console.log(found);
Array find
The find() method returns the value of
the first element in the array that satisfies
the provided testing function. Otherwise
undefined is returned.
https://developer.mozilla.org/en-US/docs
/Web/JavaScript/Reference/Global_Obje
const numArray = [77, 44, 2, 162, 18, 244, 71];
cts/Array/find const over100 = numArray.find(function (el) {
console.log(el);
return el > 100;
});
Lesson Challenge
1. Transform your array with different methods.
2. Try to combine two arrays
3. Search an array with numbers return the
value that matches the find.
Do Loop -
let x = 0;
while (x < 5) {
x++;
console.log('While Loop Count at ' + x);
}
let i = 0;
do {
i += 1;
console.log('Do While Loop Count at ' + i);
} while (i < 5);
Challenge #4 - Loops Array builder
Create an array that contains objects
created dynamically using a loop.
Output the content into the console
so it looks like the example on the
right.
}
console.log(myWork);
const getTrue = myWork.filter(function (el) {
return el.status
})
console.log(getTrue);
JavaScript Loops and iteration
● Loop Array objects forEach
● Loop Object contents for in
forEach looping array contents
The forEach() method executes a provided
function once for each array element.
console.log(Math.floor(5.05));
The Math.floor() function returns the largest integer // expected output: 5
console.log(Math.ceil(-7.004));
// expected output: -7
Math Random
Let you generate a random value. A floating-point, function getRandomInt(max) {
pseudo-random number between 0 (inclusive) and return Math.floor(Math.random() * Math.floor(max));
}
1 (exclusive).
console.log(getRandomInt(3));
// expected output: 0, 1 or 2
https://developer.mozilla.org/en-US/docs/Web/Java
console.log(getRandomInt(1));
Script/Reference/Global_Objects/Math/random // expected output: 0
Thank you
This ebook uses https://developer.mozilla.org/en-US/docs/Web/JavaScript as a source for examples. Check out
more about JavaScript at MDN.
https://www.udemy.com/javascript-cou
rse-projects