DEV Community

Cover image for JavaScript basics for future me 👽
Margarita Potylitsyna
Margarita Potylitsyna

Posted on • Edited on

JavaScript basics for future me 👽

Get started:

Link css-stylesheet and js-file

<!-- index.html -->
<head>
  <link rel="stylesheet" href="index.css">
</head>
<body>
  <script src="index.js"></script>
</body>
Enter fullscreen mode Exit fullscreen mode

Run live server:

npm install -g live-server
// then
live-server
Enter fullscreen mode Exit fullscreen mode

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

node index.js
Enter fullscreen mode Exit fullscreen mode

To declare a variable and print it out:

// index.js
let newVariable = "value"
console.log(newVariable)
Enter fullscreen mode Exit fullscreen mode

Use const when a variable can't be reassigned:

const newVariable = "value"
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

To create a function:

Create a button in html:

<!-- index.html -->
<button onclick="startGame()">START GAME</button>
Enter fullscreen mode Exit fullscreen mode

Create a function .js file:

// index.js
function startGame() {
     // Some actions here.
}
Enter fullscreen mode Exit fullscreen mode

To get element from HTML:

Assign an id to an html-element:

<!-- index.html -->
<p id="message-el">Message here</p>
Enter fullscreen mode Exit fullscreen mode

Then link it to js-variable:

// index.js
let messageEl = document.getElementById("message-el")
Enter fullscreen mode Exit fullscreen mode

Print a new value inside an html-element:

// index.js
let newValue = "Hi there!"
messageEl.textContent = newValue
Enter fullscreen mode Exit fullscreen mode

For-loop:

To count from 1 to 100 with:

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

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()
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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' ]
Enter fullscreen mode Exit fullscreen mode

Event Listener:

Create a button in HTML with ID:

<!-- index.html -->
<button id="input-btn">SAVE INPUT</button>
Enter fullscreen mode Exit fullscreen mode

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")
})
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 += `<img class="team-img" src="${imgs[i]}"></img>`
    }
    containerEl.innerHTML = imgsDOM
}

renderImage()
Enter fullscreen mode Exit fullscreen mode

HTML:

<!-- index.html -->
<html>
    <head>
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <h1>The Brooklyn Agency</h1>
        <div id="container">
            <!-- <img class="team-img" src="images/hip1.png">
            <img class="team-img" src="images/hip2.png">
            <img class="team-img" src="images/hip3.png"> -->
        </div>
        <script src="index.js"></script>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)