JavaScript basics for future me

Get started: Link css-stylesheet and js-file Run live server: npm install -g live-server // then live-server Then open View > Developer > Developer tools > Console Run js-file in the terminal: node index.js To declare a variable and print it out: // index.js let newVariable = "value" console.log(newVariable) Use const when a variable can't be reassigned: const newVariable = "value" To convert data and find out the type: let myLeads = ["www.myawsomeleads.com"] myLeads = JSON.stringify(myLeads) // converts array into string myLeads = JSON.parse(myLeads) // converts string into array console.log(typeof myLeads) To create a function: Create a button in html: START GAME Create a function .js file: // index.js function startGame() { // Some actions here. } To get element from HTML: Assign an id to an html-element: Message here Then link it to js-variable: // index.js let messageEl = document.getElementById("message-el") Print a new value inside an html-element: // index.js let newValue = "Hi there!" messageEl.textContent = newValue For-loop: To count from 1 to 100 with: // index.js for ( let count = 10; count ` } containerEl.innerHTML = imgsDOM } renderImage() HTML: The Brooklyn Agency CSS: /* index.css */ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: whitesmoke; text-align: center; color: #130e0f; } h1 { font-weight: 200; letter-spacing: 2px; } #container { width: 100%; } .team-img { width: 100px; border-radius: 100%; margin: 10px; }

Apr 29, 2025 - 21:30
 0
JavaScript basics for future me

Get started:

Link css-stylesheet and js-file



   rel="stylesheet" href="index.css">


  

Run live server:

npm install -g live-server
// then
live-server

Then open View > Developer > Developer tools > Console
Run js-file in the terminal:

node index.js

To declare a variable and print it out:

// index.js
let newVariable = "value"
console.log(newVariable)

Use const when a variable can't be reassigned:

const newVariable = "value"

To convert data and find out the type:

let myLeads = ["www.myawsomeleads.com"]
myLeads = JSON.stringify(myLeads) // converts array into string
myLeads = JSON.parse(myLeads) // converts string into array

console.log(typeof myLeads)

To create a function:

Create a button in html:


 onclick="startGame()">START GAME

Create a function .js file:

// index.js
function startGame() {
     // Some actions here.
}

To get element from HTML:

Assign an id to an html-element:


 id="message-el">Message here

Then link it to js-variable:

// index.js
let messageEl = document.getElementById("message-el")

Print a new value inside an html-element:

// index.js
let newValue = "Hi there!"
messageEl.textContent = newValue

For-loop:

To count from 1 to 100 with:

// index.js
for ( let count = 10;  count < 101;  count += 10 )  {
    console.log(count)
}

To display an array of card numbers (functions should be linked to the buttons in html-file):

let cards = [firstCard, secondCard]

function renderGame() {
  cardsEl.textContent = "Cards: " 

  for (let i = 0; i < cards.length; i++) {
      cardsEl.textContent += cards[i] + " "
  }
}

function newCard() {
    let card = getRandomCard()
    sum += card
    cards.push(card)

    renderGame()
}

Math object:

Math.random() // 0.000 - 0.999
Math.random() * 6 // 0.000 - 5.999
Math.floor(Math.random() * 6) + 1 // 1 - 6
Math.floor(3.45632) // Removes decimals. Returns 3 

totalPrice = 420.69235632455
totalPrice.toFixed(2) // Rounds to two decimals. Returns 420.69

Array methods:

let largeCountries = ["Tuvalu","India","USA","Indonesia","Monaco"]

largeCountries.pop() // delete last element of an array
largeCountries.push("Pakistan") // add element to the end
largeCountries.shift() // delete first element of an array
largeCountries.unshift("China") // add element to the beginning
console.log(largeCountries) // [ 'China', 'India', 'USA', 'Indonesia', 'Pakistan' ]

Event Listener:

Create a button in HTML with ID:


 id="input-btn">SAVE INPUT

Use ID in JS:

//index.js
let inputBt = document.getElementById("input-btn")

inputBt.addEventListener("click", function() {
    console.log("Button clicked from addEventListener")
})

// double clicked
inputBt.addEventListener("dblclick", function() {
    console.log("Button double clicked from addEventListener")
})

Simple challenge #1:

// The generateSentence(desc, arr) takes two parameterer: a description and an array.
// It should return a string based upon the description and array.

// Example 1: if you pass in "largest countries",and ["China", "India", "USA"],
// it should return the string: "The 3 largest countries are China, India, USA"

// Example 2:If you pass in "best fruits" and ["Apples", "Bananas"], it should return:
// "The 2 best fruits are Apples, Bananas"

// Use both a for loop and a template string to solve the challenge

function generateSentence(desc, arr) {
    let baseString = `The ${arr.length} ${desc} are `
    const lastIndex = arr.length - 1
    for (let i = 0; i < arr.length; i++) {
        if (i === lastIndex) {
            baseString += arr[i]
        } else {
            baseString += arr[i] + ", "
        }
    }
    return baseString
}

const sentence1 = generateSentence("highest mountains", ["Mount Everest", "K2"])
console.log(sentence1) // The 2 highest mountains are Mount Everest, K2

const sentence2 = generateSentence("largest countries", ["China", "India", "USA"])
console.log(sentence2) // The 3 largest countries are China, India, USA

const sentence3 = generateSentence("best fruits", ["Apples", "Bananas"])
console.log(sentence3) // The 2 best fruits are Apples, Bananas

Simple challenge #2:

// index.js
// Create a function that renders the three team images
// Use a for loop, template strings (``), plus equals (+=)
// .innerHTML to solve the challenge.

const imgs = [
    "images/hip1.png",
    "images/hip2.png",
    "images/hip3.png"
]

let containerEl = document.getElementById("container")

function renderImage() {
    let imgsDOM = ""
    for (i = 0; i < imgs.length; i++) {
        imgsDOM += `${imgs[i]}">`
    }
    containerEl.innerHTML = imgsDOM
}

renderImage()

HTML:



    
         rel="stylesheet" href="index.css">
    
    
        

The Brooklyn Agency

id="container">

CSS:

/* index.css */
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: whitesmoke;
    text-align: center;
    color: #130e0f;
}

h1 {
    font-weight: 200;
    letter-spacing: 2px;
}

#container {
    width: 100%;
}

.team-img {
    width: 100px;
    border-radius: 100%;
    margin: 10px;
}