What is if else in JavaScript? In JavaScript, the if else statement is used to make decisions in your code. It allows your program to run different blocks of code depending on whether a condition is true or false. Syntax: if (condition) { // code to run if condition is true } else { // code to run if condition is false } Example 1: let age = 18; if (age >= 18) { console.log("You are an adult!"); } else { console.log("You are a minor!"); } Output: You are an adult! Example 2: Checking even or odd number let number = 7; if (number % 2 === 0) { console.log("Even number"); } else { console.log("Odd number"); } Output: Odd number #html #css #javascript #react #webDesign #wevdeveloping
Understanding if else statements in JavaScript
More Relevant Posts
-
Exploring Different Methods to Calculate the Sum of Two Numbers in JavaScript When it comes to adding two numbers in JavaScript, there are various approaches to achieve the result. One common method involves defining variables for the numbers, such as: var a = 2; var b = 3; function sum(){ return a + b; } sum(); Alternatively, you can directly pass the numbers into a function for instant calculation: function sum(a, b){ return a + b; } sum(2, 3); For real-time feedback while coding, utilizing "console.log" can display the result promptly: function sum(a, b){ console.log(a + b); } sum(2, 3); Remember, JavaScript's case sensitivity emphasizes the importance of accurately typing uppercase and lowercase letters in your code. Stay precise for seamless execution! #JavaScriptTips #CodingMethods #JavaScript
To view or add a comment, sign in
-
What is String Concatenation in JavaScript? String concatenation means joining two or more strings (text values) together into one string. Why it’s used We use string concatenation when we want to: Combine multiple pieces of text together Insert variable values inside text Example 1: let firstName = "Maruf"; let lastName = "Hossen"; let fullName = firstName + " " + lastName; console.log(fullName); Output: Maruf Hossen Example 2: let name = "Maruf"; let age = 25; let info = `My name is ${name} and I am ${age} years old.`; console.log(info); Output: My name is Maruf and I am 25 years old. #html #css #javascript #react #webdesign #webdeveloping
To view or add a comment, sign in
-
-
Reflection & Object Composition in Modern JavaScript In JavaScript, objects don’t just store values — they can look at themselves and manipulate their own properties. That’s the power of Reflection. Reflection enables patterns like Object Composition, a clean, modern alternative to long prototype chains. Reflection in Action const john = { firstname: "John", lastname: "Doe" }; for (let prop in john) { if (john.hasOwnProperty(prop)) { console.log(prop + ": " + john[prop]); } } Output: firstname: John lastname: Doe Object Composition — the ES6+ Way Instead of relying on libraries like Lodash or Underscore, modern JS gives us built-ins: 1️⃣ Object.assign() Object.assign(john, { address: "123 Main St" }, { getFirstName() { return this.firstname; } }); 2️⃣ Spread Operator (ES2018) const extendedJohn = { ...john, address: "123 Main St", getFirstName() { return this.firstname; } }; Object.assign() → Mutates the object Spread { ...obj } → Creates a new one Why It Matters No external libraries needed Clean, readable syntax Full control over mutation or immutability 100% native and widely supported Takeaway: With ES6+, Object.assign() and the spread operator { ...obj } give you all the power of extend, natively — Reflection + Composition, the modern way. #JavaScript #ES6 #FrontendDevelopment #WebDevelopment #CleanCode #ProgrammingTips #React #TypeScript
To view or add a comment, sign in
-
JavaScript Block-Level Variables JavaScript ES6 introduced block-level scoping with the let and const keywords. Block-level variables are accessible only within the block {} they are defined in, which can be smaller than a function's scope. For example, function display_scopes() { // declare variable in local scope let message = "local"; if (true) { // declare block-level variable let message = "block-level"; console.log(`inner scope: ${message}`); } console.log(`outer scope: ${message}`); } display_scopes(); Output inner: block-level outer: local In this example, we have created two separate message variables: Block-Level: The variable inside the if block (visible only there). Local-Level: The variable inside the display_scopes() function.
To view or add a comment, sign in
-
-
✨I am excited to share about stages of errors in javascript. while learning JavaScript,i realized that errors are not just mistakes-they are an important part of how code works and how we debug efficiently. Types of errors in javascript: ➡️Syntax error:This happens before the code runs,when javascript checks the syntax. ex:console.log("Hello" //syntaxerror:missing paranthesis ➡️ Reference error:This error occurs while the program is running -after syntax checking ex: console.log(x) //reference error:x is not defined. ➡️Type error:A type error occurs when an operation or function is applied to a value of the wrong type. ex:let person console.log(person.name)//Type error: cannot read properties of undefined. ➡️A URI(Uniform Resource Identifier) occurs when a malformed uri is passed to a URI handling function. ex:decodeURI('%');//uri error:uri malformed ➡️Range error:A range error occurs when you give a function a value that's outside it's valid range,even though the type is correct. ex:let arr=new array(-2)//range error: Invalid array length #Javascript #webdevelopment #coding #Learningjourney #Debugging #10000coders #sudheervelpula
To view or add a comment, sign in
-
-
Just finished implementing a simple, yet foundational, counter using pure JavaScript! 🚀 It’s a perfect example of how straightforward DOM manipulation and event listeners can be. No frameworks needed to manage this state—just the basics, done right. Key takeaway for beginners: Mastering addEventListener() is crucial for making your web pages interactive. This simple pattern of selecting elements (document.querySelector), changing a variable (count), and updating the UI (element.innerHTML = count) is the backbone of dynamic web development. JavaScript // Code Snippet let ins = document.querySelector("#ins"); let dec = document.querySelector("#dec"); let reset = document.querySelector("#reset"); let overlay = document.querySelector(".bg-ovverlay .text"); let main = document.querySelector(".box .text"); let count = 0; ins.addEventListener("click", () => { count++; overlay.innerHTML = count; main.innerHTML = count; }); dec.addEventListener("click", () => { count--; overlay.innerHTML = count; main.innerHTML = count; }); reset.addEventListener("click", () => { count = 0; overlay.innerHTML = count; main.innerHTML = count; }); What's the smallest piece of code that taught you the most about JavaScript? Share below! 👇 #JavaScript #WebDevelopment #DOMManipulation #EventHandling #Coding #Programming #FrontEnd #day43 #SheryiansCodingSchool #Cohort2
To view or add a comment, sign in
-
Arrow Functions vs Regular Functions in JavaScript ⚔️ They look similar, right? But under the hood, arrow functions and regular functions behave very differently — especially when it comes to this, arguments, and constructors. Let’s break it down 👇 1️⃣ 'this' Binding 👉 Regular functions have their own this — it depends on how the function is called. 👉 Arrow functions don’t have their own this; they inherit it from the enclosing scope. 💡 When to use which: • Use a regular function when you need dynamic this (methods, event handlers, etc.). • Use an arrow function when you want lexical this (callbacks, promises, or closures). 2️⃣ 'arguments' Object Regular functions get an implicit arguments object. Arrow functions don’t — they rely on rest parameters if you need access to arguments. 3️⃣ Constructors Regular functions can be used as constructors with new. Arrow functions cannot — they don’t have a prototype. 👉 Which one do you prefer using in your daily JavaScript code — and why? #JavaScript #NodeJS #Frontend #Backend #SoftwareEngineering #CleanCode #ArrowFunction #RegularFunction #SoftwareEngineer
To view or add a comment, sign in
-
Going back to basics 🌱 When you copy an object or array in Javascript are you really creating a new copy, or just another reference to the same memory? That’s where "Shallow Copy" and "Deep Copy" come into play. A "Shallow Copy" creates a new object, but only copies the top level properties "nested objects" or "arrays" are still linked by reference. So, if you change a nested value in the copied object,it also affects the original one. On the other hand, a "Deep Copy" creates a completely independent clone all "nested values" are copied as well. This means both the original and the copy live their own separate lives. Below I have added a simple example to show what is happening in both cases - // Shallow Copy Here, we used the "spread operator (...)" to copy the object but since it’s a shallow copy, the nested details object still points to the same reference. // Deep Copy Here, we used "JSON.parse(JSON.stringify())" to create a true clone, this process "breaks the reference", making both objects completely independent. I also got to know there are a few other ways to deep copy like using "structuredClone(obj)" a newer built in method in modern JS or "lodash.cloneDeep(obj)" for more complex structures , will read about them. #JavaScript #Frontend
To view or add a comment, sign in
-
-
Why You Should Avoid Using new Number(), new String(), and new Boolean() in JavaScript In JavaScript, there is an important distinction between primitive values and object wrappers. Consider the following example: let a = 3; // primitive number let b = new Number(3); // Number object console.log(a == b); // true (type coercion) console.log(a === b); // false (different types) This inconsistency occurs because new Number(), new String(), and new Boolean() create objects, not primitive values. Although they appear similar, they can cause subtle and hard-to-detect bugs in equality checks and logical comparisons. Common Issues Confusing equality checks (== vs ===) Unintended behavior in conditionals or truthy/falsey evaluations Inconsistent data handling across the codebase Recommended Best Practices Always use literals or function calls for primitive values: // Correct usage let x = 3; let y = "Hello"; let z = true; // Safe conversions Number("3"); // → 3 (primitive) String(123); // → "123" Boolean(0); // → false Use constructors like Date, Array, Object, and Function only when you intend to create objects. For Working with Dates Instead of relying solely on the Date object, consider modern and reliable alternatives: Intl.DateTimeFormat for formatting Temporal API (in modern JavaScript runtimes) for date and time arithmetic Key Takeaway If you encounter new Number(), new String(), or new Boolean() in your codebase, it is often a sign of a potential bug. Use literals for primitives, and reserve constructors for actual objects. #JavaScript #WebDevelopment #SoftwareEngineering #ProgrammingBestPractices #CleanCode #FrontendDevelopment #NodeJS #TypeScript #Developers
To view or add a comment, sign in
-
Understanding this in JavaScript this — one of the most misunderstood keywords in JavaScript. It’s simple in theory… until it suddenly isn’t 😅 Here’s what makes it tricky — this depends entirely on how a function is called, not where it’s written. Its value changes with context. Let’s look at a few examples 👇 const user = { name: "Sakura", greet() { console.log(`Hello, I am ${this.name}`); }, }; user.greet(); // "Sakura" ✅ const callGreet = user.greet; callGreet(); // undefined ❌ (context lost) const boundGreet = user.greet.bind(user); boundGreet(); // "Sakura" ✅ (context fixed) Key takeaways 🧠 ✅ this refers to the object that calls the function. ✅ Lose the calling object → lose the context. ✅ Use .bind(), .call(), or .apply() to control it. ✅ Arrow functions don’t have their own this — they inherit from the parent scope. These small details often trip up developers in interviews and real-world debugging sessions. Once you understand the context flow, this becomes a lot less scary to work with. 💪 🎥 I simplified this in my Day 28/50 JS short video— check it out here 👇 👉 https://lnkd.in/gyUnzuZA #javascript #webdevelopment #frontend #backend #programming #learnjavascript #softwaredevelopment #developerslife #techsharingan #50daysofjavascript
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development