Setting up Javascript file
To include a JS file in an HTML code, you type the script tag before closing the body tag
<script src="index.js" ></script>
Declaring Variables
let firstName = "Henna"
let LastName = "Singh"
let fullName = firstName + " " + LastName
console.log(fullName)
Variables can be declared using let
for mutable variables and const
for immutable variables.
Declaring Functions
//1
function greeting() {
console.log("Hi there")
}
//2
const greeting = function () {
console.log("Hi there")
}
//3
const greeting = () => {
console.log("Hi there")
}
Concatenation
console.log("2" + 2) // "22"
console.log(11 + 7) // 18
console.log(6 + "5") //
console.log("My points: " + 5 + 9) //My points: 59
console.log(2 + 2) // 4
console.log("11" + "14") // 1114
If a string is added with a number, it turns to a string
DOM - Document Object Model
To make websites interactive, Javascript interacts with HTML. The HTML page is referred to as a document. There is a DOM API to understand different elements in a DOM, and with the help of Javascript, you can programmatically change them.
<body>
<img src="images/shoe.jpeg" alt="Nike shoe">
<p>Nike shoe</p>
<button onclick= showError()>Purchase - $149</button>
<p id="error"></p>
<script src="index.js"></script>
</body>
let errorMsg = document.getElementById("error");
let errorMsg = document.querySelector("#error");
function showError() {
errorMsg.textContent = "Something went wrong, please try again"
}
Comparison Operators
== compares the values
=== compares both value and type (strict match)
Arrays
let greeting = ["hello","there"] //ordered lists of data
console.log(greeting[0])
console.log(greeting[1])
//Adding Elements
greeting.push("Natalia")// adds to end of the array
greeting.unshift("Sonio") // adds to start of the array
//Remove last item of array
greeting.pop() //from end of the array
greeting.shift() // from the start of the array
Arrays are zero-indexed
composite data types
can take multiple data types: primitives or objects
Loops
for(let count =1; count < 11; count += 1) {
console.log(count)
}
Returning from a function
function greeting() {
return "Hello World"
}
console.log(greeting());
Objects
let course = {
title: "Front-end Development",
lessons: 16,
creator: "Per Harald",
length: 70,
level: 1,
isFree: false,
tags: ["html", "css", "javascript"]
}
complex/composite data types
store data in-depth
key-value pairs
Generating Random Numbers
Math.random() // 0 - 0.999999
Math.random() * 4 // 0 - 3.9999
Math.floor(Math.random() * 4) // 0 - 3
Check how I used these concepts to create a Blackjack App with just vanilla Javscript