≡ Menu

JavaScript, while flexible and powerful, has its fair share of nuances that can trip even seasoned developers. Let’s dive into some of these tricky areas.

Type Coercion & Comparisons

  1. Question: What is the result of ‘5’ + 3? Answer: ’53’. JavaScript coerces the number 3 to a string and concatenates it with ‘5’.
  2. Question: What is the result of ‘5’ – 3? Answer: 2. JavaScript coerces the string ‘5’ to a number before performing the subtraction.
  3. Question: What is the result of 1 + ‘2’ + 3? Answer: ‘123’. The first + coerces 1 to a string, and then the subsequent + performs string concatenation.
  4. Question: What is the result of 3 + ‘2’ – 1? Answer: 31. 3 + ‘2’ becomes ’32’, and then ’32’ – 1 coerces ’32’ to a number, resulting in 31.
  5. Question: What is the result of [] == false? Answer: true. The empty array [] is coerced to 0 when compared to a number, and false is also coerced to 0.
  6. Question: What is the result of [] == ![]? Answer: true. ![] evaluates to false. As seen above, [] == false is true.
  7. Question: What is the result of {} == false? Answer: false. The object {} is coerced to NaN when compared numerically, and NaN == 0 is false.
  8. Question: What is the result of null == undefined? Answer: true. This is a special case in JavaScript’s loose equality.
  9. Question: What is the result of null === undefined? Answer: false. The strict equality operator (===) checks both value and type without coercion, and null and undefined are different types.
  10. Question: What is the result of NaN == NaN? Answer: false. NaN is not equal to itself.

Scope & Closures

  1. Question: What will the following code output?

    for (var i = 0; i < 5; i++) {
      setTimeout(function() {
        console.log(i);
      }, i * 100);
    }
    

    Answer: 5 will be logged five times. Because var has function scope (or global scope outside a function), the loop completes, and the value of i is 5 before any of the setTimeout callbacks execute.

  2. Question: How can you modify the previous code to log 0, 1, 2, 3, 4?Answer: Use let instead of var, or create a closure within the loop:
    // Using let
    for (let i = 0; i < 5; i++) {
      setTimeout(function() {
        console.log(i);
      }, i * 100);
    }
    
    // Using a closure
    for (var i = 0; i < 5; i++) {
      (function(j) {
        setTimeout(function() {
          console.log(j);
        }, j * 100);
      })(i);
    }
    
  3. Question: What will the following code output?

    var a = 10;
    function foo() {
      console.log(a);
      var a = 20;
    }
    foo();
    

    Answer: undefined. Due to hoisting, the var a = 20; inside foo is moved to the top of the function scope. So, console.log(a) is executed before a is actually assigned the value 20.

  4. Question: What is a closure in JavaScript?

Answer: A closure is a function bundled together with its surrounding state (lexical environment). This means a closure can remember and access variables from its outer function’s scope even after the outer function has finished executing.

15. Question: What will the following code output?

function outer() {
  var count = 0;
  function inner() {
    count++;
    console.log(count);
  }
  return inner;
}
var increment = outer();
increment();
increment();

Answer: 1 then 2. The inner function forms a closure over the count variable in the outer function’s scope. Each call to increment (which refers to the inner function) increments and logs the same count variable.

this Keyword

  1. Question: What does the this keyword refer to in a regular function call?Answer: In non-strict mode, this refers to the global object (window in browsers, global in Node.js). In strict mode (‘use strict’), this is undefined.
  2. Question: What does the this keyword refer to inside a method of an object?Answer: It refers to the object that the method is called on.
  3. Question: How does this behave inside an arrow function?Answer: Arrow functions do not have their own this binding. They lexically inherit the this value from their surrounding scope.
  4. Question: How can you explicitly set the value of this for a function call?Answer: Using the call(), apply(), or bind() methods.
  5. Question: What will the following code output?

    const obj = {
      name: 'Alice',
      greet: function() {
        setTimeout(function() {
          console.log('Hello, ' + this.name);
        }, 100);
      }
    };
    obj.greet();
    

    Answer: 'Hello, undefined' (in non-strict mode in a browser). Inside the setTimeout callback, this refers to the global window object, which doesn’t have a name property.

  6. Question: How can you fix the this issue in the previous question?Answer: Several ways:
    • Using an arrow function in setTimeout:
      const obj = {
        name: 'Alice',
        greet: function() {
          setTimeout(() => {
            console.log('Hello, ' + this.name);
          }, 100);
        }
      };
      
    • Using bind(this):

       

      const obj = {
        name: 'Alice',
        greet: function() {
          setTimeout(function() {
            console.log('Hello, ' + this.name);
          }.bind(this), 100);
        }
      };
      
    • Storing this in a variable:
      const obj = {
        name: 'Alice',
        greet: function() {
          const self = this;
          setTimeout(function() {
            console.log('Hello, ' + self.name);
          }, 100);
        }
      };
      

Promises & Async/Await

  1. Question: What is the state of a Promise when it’s first created? Answer: pending.
  2. Question: What are the possible states of a settled Promise? Answer: fulfilled (or resolved) and rejected.
  3. Question: What is the purpose of the then() method of a Promise? Answer: It’s used to handle the fulfillment of a Promise, receiving the resolved value. It can also return another Promise, creating a Promise chain.
  4. Question: What is the purpose of the catch() method of a Promise? Answer: It’s used to handle the rejection of a Promise, receiving the error reason.
  5. Question: What is the purpose of the finally() method of a Promise? Answer: It allows you to execute code regardless of whether the Promise was fulfilled or rejected. It doesn’t receive the final value or error.
  6. Question: What does the async keyword do? Answer: It makes a function return a Promise. If the function explicitly returns a non-Promise value, it will be wrapped in a resolved Promise.
  7. Question: What does the await keyword do? Answer: It can only be used inside an async function. It pauses the execution of the async function until the Promise it precedes settles (either resolves or rejects).
  8. Question: How do you handle errors within an async/await function?Answer: Using a try…catch block.
  9. Question: What will the following code output?

    async function example() {
      console.log('Start');
      await new Promise(resolve => setTimeout(resolve, 100));
      console.log('End');
    }
    example();
    console.log('Middle');
    

    Answer:

    Start
    Middle
    End
    

    The await pauses the example function, but the synchronous console.log('Middle') runs immediately.

Object Properties & Prototypes

  1. Question: What is the difference between obj.property and obj[‘property’]?Answer: Both are used to access object properties. However, obj[‘property’] allows you to use variable property names or property names that are not valid JavaScript identifiers (e.g., containing spaces).
  2. Question: What is the purpose of the Object.keys() method? Answer: It returns an array of a given object’s own enumerable property names, in the order they are iterated over in a loop.
  3. Question: What is the prototype chain in JavaScript? Answer: It’s a mechanism for object inheritance. When you try to access a property of an object, JavaScript first looks at the object itself. If the property1 is not found, it searches the object’s prototype, then the prototype’s prototype, and so on, until it finds the property or reaches the2 end of the chain (null).
  4. Question: How can you set the prototype of an object? Answer: Using Object.setPrototypeOf(obj, prototype) or by using Object.create(prototype) when creating the object.
  5. Question: What is the difference between hasOwnProperty() and in operator? Answer: hasOwnProperty() returns true if the object has the specified property as a direct property (not inherited through the prototype chain). The in operator returns true if the specified property is in the object or its prototype chain.
  6. Question: What will the following code output?

    function Foo() {
      this.value = 42;
    }
    Foo.prototype.value = 99;
    const bar = new Foo();
    console.log(bar.value);
    

    Answer: 42. When new Foo() is called, the Foo constructor is executed, and this.value = 42 sets the value property directly on the bar object, overriding the prototype property.

Arrays

  1. Question: What is the result of [1, 2, 3] + [4, 5, 6]? Answer: ‘1,2,34,5,6’. JavaScript converts the arrays to strings using their toString() method and then concatenates them.
  2. Question: What is the difference between slice() and splice() array methods? Answer:
    • slice() returns a new array containing a portion of the original array. It does not modify the original array.
    • splice() changes the contents of an array by removing or replacing existing elements and/or3 adding new elements in place. It returns an array4 containing the deleted elements.

 

39. Question: How do you empty an array in JavaScript? List at least three ways.

Answer:

    • arr.length = 0;
    • arr.splice(0, arr.length);
    • arr = []; (This creates a new empty array and reassigns the variable, but doesn’t affect other references to the original array).

40 . Question: What will the following code output?

const arr = [1, 2, 3];
arr[10] = 5;
console.log(arr.length);

Answer: 11. JavaScript allows you to set elements at arbitrary indices, and the length property is updated to reflect the highest index plus one. The elements at indices 3 through 9 will be undefined.

Tricky Bits & Edge Cases

  1. Question: What is the result of 0.1 + 0.2 == 0.3? Answer: false. Due to floating-point precision issues, 0.1 + 0.2 results in a value slightly different from 0.3.
  2. Question: What is the output of typeof NaN? Answer: ‘number’. This is a well-known quirk of JavaScript.
  3. Question: What is the output of typeof null? Answer: ‘object’. This is another historical quirk in JavaScript.
  4. Question: What is the difference between map() and forEach() array methods?Answer:
    • map() creates a new array by calling a provided function on every element in the calling array.
    • forEach() executes a provided5 function once for each array element but does not create a new array. It returns undefined.

 

45. Question: What is the purpose of the use strict directive?

Answer: It enables “strict mode” in JavaScript, which enforces stricter parsing and error handling on your code. It helps to catch common coding mistakes and “unsafe” actions.

46. Question: What are the falsy values in JavaScript?

Answer: false, null, undefined, 0, NaN, and ” (empty string). All other values are truthy.

47. Question: What is the difference between let, const, and var?

Answer:

    • var has function scope (or global scope outside a function) and is hoisted.
    • let has block scope and is hoisted but not initialized (you can’t use it before its declaration). It can be reassigned.
    • const has block scope and is hoisted but not initialized. It cannot be reassigned after its initial assignment.

 

48. Question: What will the following code output?

console.log(1 < 2 < 3);
console.log(3 > 2 > 1);

Answer:

true
false

For 1 < 2 < 3, it evaluates as (1 < 2) < 3, which is true < 3. true is coerced to 1, so 1 < 3 is true.

For 3 > 2 > 1, it evaluates as (3 > 2) > 1, which is true > 1. true is coerced to 1, so 1 > 1 is false.

49. Question: What is event bubbling and event capturing in the DOM?

Answer:

    • Event Bubbling: The event propagates upwards through the DOM tree, from the target element to its parent, and so on, up to the document.
    • Event Capturing: The event propagates downwards through the DOM tree, starting from the window, then the document, and down to the target element. Event listeners are triggered in this order.

 

50. Question: What is the output of the following code?

function sayHi() {
  console.log(name);
  console.log(age);
  var name = 'Lydia';
  let age = 21;
}
sayHi();

Answer:

undefined
ReferenceError: Cannot access 'age' before initialization

name is declared with var, so it’s hoisted, but not initialized until the line var name = 'Lydia'; is reached. age is declared with let, which is also hoisted but not initialized, leading to a ReferenceError when you try to access it before its declaration.

Wrapping Up

JavaScript’s intricacies can be both fascinating and frustrating. By understanding these tricky questions and their underlying concepts, you’ll be better equipped to write more robust and predictable code. Keep practicing and exploring, and you’ll master the nuances of this powerful language!

{ 0 comments }

It seems like we live in a negative world so a little spark of inspiration can go a long way.

Random quote generators have become ubiquitous tools, offering snippets of wisdom, humor, or profound thought at the click of a button.

These seemingly simple applications are a fantastic way to learn the fundamental building blocks of web development: HTML for structure, CSS for styling, and JavaScript for dynamic behavior.

This comprehensive guide will walk you through the process of creating your own random quote generator from scratch.

We’ll delve into each language, explaining the code step-by-step, and by the end, you’ll have a functional and stylish application that can brighten your day or the day of your website visitors.

Attention:Click here if you need a money making website for your business!

1. Laying the Foundation: HTML Structure (index.html)

Our journey begins with HTML, the skeleton of our web page. We need to define the basic elements that will hold our quote and the button to generate a new one. Create an index.html file and populate it with the following structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Quote Generator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div id="quote-container">
            <p id="quote-text"></p>
            <p id="quote-author"></p>
        </div>
        <button id="new-quote-btn">New Quote</button>
    </div>
    <script src="script.js"></script>
</body>
</html>

Let’s break down this HTML:

  • <!DOCTYPE html> and <html lang="en">: These are standard HTML declarations defining the document type and language.
  • <head>: This section contains meta-information about the HTML document:
    • <meta charset="UTF-8">: Specifies the character encoding for the document.
    • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Configures the viewport for responsive design.
    • <title>Random Quote Generator</title>: Sets the title that appears in the browser tab.
    • <link rel="stylesheet" href="style.css">: Links our external CSS file (style.css) for styling.
  • <body>: This section contains the visible content of our web page:
    • <div class="container">: A main container to hold all the elements and allow for centralized styling.
    • <div id="quote-container">: A container specifically for the quote and author text.
      • <p id="quote-text"></p>: An empty paragraph element where the actual quote will be displayed. It has the ID quote-text for easy targeting with JavaScript.
      • <p id="quote-author"></p>: An empty paragraph element to display the author of the quote, also with a unique ID quote-author.
    • <button id="new-quote-btn">New Quote</button>: A button that, when clicked, will trigger the generation of a new random quote. It has the ID new-quote-btn.
    • <script src="script.js"></script>: Links our external JavaScript file (script.js) which will contain the logic for fetching and displaying the quotes. Placing the script tag at the end of the <body> ensures that the HTML elements are loaded before the JavaScript tries to interact with them.

2. Adding Style: CSS Styling (style.css)

Now that we have the basic structure, let’s make it visually appealing with CSS.

Create a style.css file in the same directory as your index.html and add the following styles:

body {
    font-family: sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #f0f0f0;
    margin: 0;
}

.container {
    background-color: #fff;
    padding: 40px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    text-align: center;
    width: 80%;
    max-width: 600px;
}

#quote-container {
    margin-bottom: 30px;
}

#quote-text {
    font-size: 1.5em;
    line-height: 1.6;
    margin-bottom: 15px;
    color: #333;
}

#quote-author {
    font-style: italic;
    color: #777;
    text-align: right;
}

#new-quote-btn {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 5px;
    font-size: 1em;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

#new-quote-btn:hover {
    background-color: #0056b3;
}

Here’s a breakdown of the CSS:

  • body: Styles the entire body of the page, setting a sans-serif font, centering the content horizontally and vertically using Flexbox, setting a minimum height to fill the viewport, a light gray background color, and removing default margins.
  • .container: Styles the main container, setting a white background, padding, rounded corners, a subtle box shadow, centered text, and a maximum width for better readability on larger screens.
  • #quote-container: Adds some bottom margin to separate the quote from the button.
  • #quote-text: Styles the quote text with a larger font size, increased line height for readability, bottom margin, and a dark gray color.
  • #quote-author: Styles the author text with italic font style, a lighter gray color, and right alignment.
  • #new-quote-btn: Styles the “New Quote” button with a blue background, white text, no border, padding, rounded corners, a standard font size, a pointer cursor on hover, and a smooth transition for the hover effect.
  • #new-quote-btn:hover: Defines the style when the mouse hovers over the button, changing the background color to a darker shade of blue.

3. Adding Interactivity: JavaScript Logic (script.js)

Now for the magic! We’ll use JavaScript to fetch our quotes and dynamically update the HTML.

Create a script.js file in the same directory and add the following code:

const quoteText = document.getElementById('quote-text');
const quoteAuthor = document.getElementById('quote-author');
const newQuoteBtn = document.getElementById('new-quote-btn');

const quotes = [
    {
        text: "The only way to do great work is to love what you do.",
        author: "Steve Jobs"
    },
    {
        text: "Strive not to be a success, but rather to be of value.",
        author: "Albert Einstein"
    },
    {
        text: "The mind is everything. What you think you become.",
        author: "Buddha"
    },
    {
        text: "Two roads diverged in a wood, and I—I took the one less traveled by, And that has made all the difference.",
        author: "Robert Frost"
    },
    {
        text: "The best time to plant a tree was 20 years ago. The second best time is now.",
        author: "Chinese Proverb"
    }
    // Add more quotes here!
];

function getRandomQuote() {
    const randomIndex = Math.floor(Math.random() * quotes.length);
    return quotes[randomIndex];
}

function displayQuote() {
    const currentQuote = getRandomQuote();
    quoteText.textContent = currentQuote.text;
    quoteAuthor.textContent = `- ${currentQuote.author}`;
}

newQuoteBtn.addEventListener('click', displayQuote);

// Initial quote display when the page loads
displayQuote();

Let’s dissect this JavaScript:

  • const quoteText = document.getElementById('quote-text');, const quoteAuthor = document.getElementById('quote-author');, const newQuoteBtn = document.getElementById('new-quote-btn');:1 These lines use document.getElementById() to get references to the HTML elements we want to manipulate using their unique IDs. We store these references in constant variables for easier access.
  • const quotes = [...]: This is an array of JavaScript objects. Each object represents a quote and has two properties: text (the actual quote) and author (the person who said it). You can expand this array with as many quotes as you like.
  • function getRandomQuote() { ... }: This function is responsible for selecting a random quote from the quotes array:
    • Math.random(): Generates a floating-point, pseudo-random number in the range 0 (inclusive) up to but not including 1.
    • quotes.length: Gets the total number of quotes in the array.
    • Math.random() * quotes.length: Multiplies the random number by the number of quotes, resulting in a random floating-point number between 0 (inclusive) and the number of quotes (exclusive).
    • Math.floor(...): Rounds the random floating-point number down to the nearest integer, giving us a valid random index for the quotes array.
    • return quotes[randomIndex];: Returns the quote object at the randomly generated index.
  • function displayQuote() { ... }: This function takes a random quote and updates the HTML elements to display it:
    • const currentQuote = getRandomQuote();: Calls the getRandomQuote() function to get a random quote object.
    • quoteText.textContent = currentQuote.text;: Sets the textContent property of the quoteText paragraph to the text of the randomly selected quote.
    • quoteAuthor.textContent =– ${currentQuote.author};: Sets the textContent property of the quoteAuthor paragraph to the author of the quote, adding a hyphen for better presentation.
  • newQuoteBtn.addEventListener('click', displayQuote);: This line attaches an event listener to the newQuoteBtn (the “New Quote” button). When the button is clicked ('click' event), the displayQuote function will be executed, fetching and displaying a new random quote.
  • displayQuote();: This line calls the displayQuote function once when the script initially loads. This ensures that a quote is displayed on the page when it first opens, rather than starting with empty quote and author fields.

Expanding and Enhancing:

This basic random quote generator provides a solid foundation. Here are some ideas for expanding and enhancing it:

  • More Quotes: The most straightforward enhancement is to add a larger and more diverse collection of quotes to the quotes array.
  • Fetching Quotes from an API: Instead of hardcoding the quotes, you could fetch them dynamically from an external API. This would allow for a constantly updating source of inspiration. You would use the fetch API in JavaScript to make HTTP requests to the quote API.
  • Social Sharing: Add buttons to allow users to easily share the displayed quote on social media platforms like Twitter or Facebook. This would involve creating links with the quote text and author pre-filled.
  • Themes and Styling Options: Allow users to customize the appearance of the quote generator by adding options to change fonts, colors, and backgrounds. This could involve adding more CSS classes and using JavaScript to toggle them.
  • Quote Categories: Organize quotes into categories (e.g., motivational, funny, philosophical) and allow users to select a specific category.
  • Local Storage: You could store recently viewed quotes in the browser’s local storage so users can revisit them.

Conclusion:

Building a random quote generator is a fantastic exercise in web development fundamentals.

By combining the structural power of HTML, the visual appeal of CSS, and the dynamic capabilities of JavaScript, you can create a simple yet engaging application. Happy coding!

{ 0 comments }