When learning JavaScript, it's easy to run into odd-looking outputs, especially when it comes to strings, numbers, and how they interact. In this quick post, we’ll walk through some basic but important concepts like variable declarations, negation, and type coercion in string and number operations.

🔹 Declaring and Negating Variables
Let’s start by declaring a variable and assigning it a number:

let value = 3;

Now, let’s create a second variable and assign it the negated version of value:

let negvalue = -value;

If you log this to the console:

console.log(negvalue); // Output: -3

This simply shows how the minus sign flips the value from positive to negative. Nothing too crazy—yet!

🔹 String Concatenation
Next, let’s explore how strings behave when combined:

let str1 = "hi";
let str2 = " ji";
console.log(str1 + str2); // Output: "hi ji"

In JavaScript, using the + operator with strings concatenates them—i.e., sticks them together in a single line.

🔹 When Strings Meet Numbers: Type Coercion at Work
This is where things get interesting. JavaScript has a feature called type coercion, which means it automatically converts types when it thinks it’s needed—sometimes with unexpected results.

*Here are a few examples:
*

console.log("1" + 2);      // Output: "12"
console.log("1" + "2");    // Output: "12"
console.log(1 + "2" + 1);  // Output: "121"
console.log(1 + 2 + "2");  // Output: "32"

Let’s break those down:

"1" + 2 → The number 2 is coerced into a string → "1" + "2" → "12"
1 + "2" + 1 → 1 + "2" becomes "12" → "12" + 1 becomes "121" → Everything after a string turns into string concatenation
1 + 2
  • "2" → 1 + 2 is 3 (because both are numbers) → 3 + "2" becomes "32" JavaScript reads operations left to right, and coercion kicks in as soon as a string gets involved.

Final thaught:
Understanding how JavaScript handles basic operations like negation and string/number coercion can save you from bugs and confusion later on. The language’s flexibility is powerful, but with great power comes great... weird behaviour. 😄

If you're new to JS or brushing up your skills, take time to test these concepts out in the console. JavaScript's quirks become a lot more predictable once you see the logic behind them.