DEV Community

Shifa
Shifa

Posted on

“How One Tiny ! Can Break (or Save) Your JavaScript Code 💥”

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

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

let negvalue = -value;

Enter fullscreen mode Exit fullscreen mode

If you log this to the console:

console.log(negvalue); // Output: -3
Enter fullscreen mode Exit fullscreen mode

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";

Enter fullscreen mode Exit fullscreen mode
console.log(str1 + str2); // Output: "hi ji"

Enter fullscreen mode Exit fullscreen mode

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"

Enter fullscreen mode Exit fullscreen mode

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 Thoughts

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.

For source Code: https://github.com/shifa-23/JS-vault/blob/main/basics1/operation.js

Top comments (0)