Indentation differences between PHP and JavaScript

It's interesting to observe the different indentation conventions in various programming languages. Recently, I came across a code snippet from the PHP manual that caught my attention:

switch ($i) {
    case "apple":
        echo "i is apple";
        break;
    case "bar":
        echo "i is bar";
        break;
    case "cake":
        echo "i is cake";
        break;
}

The indentation of each case statement being inside the switch block seems logical as it enhances readability and clearly shows the structure.

However, when I tested a similar JavaScript switch statement in JSLint:

switch (i) {
    case "apple":
        alert("i is apple");
        break;
    case "bar":
        alert("i is bar");
        break;
    case "cake":
        alert("i is cake");
        break;
}

JSLint flagged an error suggesting that the code should be formatted like this instead:

switch (i) {
case "apple":
    alert("i is apple");
    break;
case "bar":
    alert("i is bar");
    break;
case "cake":
    alert("i is cake");
    break;
}

This new layout aligns each case statement with the switch block, which feels unconventional and not as clear as the previous version. Is JSLint simply following a specific convention or is there a deeper reason why the indentation differs?

Answer №1

Feel free to style your code in a way that suits you best. While jsLint is recommended for checking, don't feel pressured to follow all its suggestions if you believe they don't enhance your code quality. Remember, it's okay if jsLint's feedback hurts your ego.

Answer №2

According to Crockford's principles, blocks in programming do not create a new scope. He emphasizes that blocks should be used with function, if, switch, while, for, do, and try statements only.

Crockford also recommends the following structure for blocks:

if (condition){
    statements; 
}

He believes this method is "more resilient" and has been intentionally designed this way.

Answer №3

It's important to follow your own logical reasoning when deciding how to indent code. If a tool like JSLint is overly critical of your indentation choices, it may be too strict.

Answer №4

While consistency is essential, at the end of the day it's all about your personal preferences. Feel free to format your code in a way that suits you best. The formatting style you opt for is entirely up to you, as there are many different styles that can be considered "good". However, it is crucial that any chosen formatting style remains consistent - stick to the rules you prefer and follow them diligently.

It's amusing how heated debates often arise over seemingly trivial matters such as whether to place { on the same line as preceding code or not, or the concept of "cuddling curly braces" around an else. Personally, I believe only strict adherents would place a { on the same line as their if statement. :)

Answer №5

When it comes to coding in JavaScript, following conventions is key (as defined by JSLint). In my opinion, PHP may not necessarily adhere to the same conventions (I'm not sure if the manual provides any guidelines, but I do know that the standard library does not). Personally, I lean towards the JS style because things can quickly get messy when dealing with multiple nested blocks. Here's an example of what I mean (using PHP code):

class Foo{
     function Bar($arr) {
         foreach($arr as $item) {
             switch ($item) {
                 case "foo":
                      // Do something
                      break;
                      // You see where this is going

In the end, the choice is yours. I wouldn't recommend using the PHP manual as a strict style guide; if you find yourself working with multiple languages, sticking to the well-established JS style might be more efficient.

Answer №6

When JavaScript and PHP are interpreted, any extra whitespace is automatically removed. This means that you can write your code in a way that might seem messy to others, but it will still work just fine. Personally, I like to include extra curly brackets in my switch statements to avoid missing fall-through errors:

switch ($someVar)
{
  case 'value':
  {
    //your code here
  } break;
  case 'something':
  {
    //more code here
  }
  case 'something else':
  {
    //some more code here
  } break;
  default:
  {
    //default code here
  } break;
}

By scanning down the code at the end braces, I can easily check if I have included the necessary break statements. In this example, you can see that the 'something' case is missing a break statement (possibly intentionally or accidentally).

Some people may not agree with this coding format, but ultimately what matters is finding a style that works best for you. The parsers for these languages are quite forgiving, so feel free to experiment and find a method that suits your preferences.

Answer №7

His expertise in Java seems to be influencing his approach. The structure he's following resembles the established Java standards for switch case. While I initially favored your initial method, I am starting to accept the JSLint methodology.

Answer №8

I was also perplexed by this issue, but I managed to find an explanation in Douglas Crockford's Code Conventions for the JavaScript Programming Language, which can be located at

In his guidelines, Crockford emphasizes that clauses (case, catch, default, else, finally) should not be indented like regular statements since they are not considered as such.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clicking a button in JavaScript can pass an ID by triggering an onClick

Here is the function that triggers when the button is clicked <button type="button" class="btn btn-info " onClick= "show('<?php echo $data ?>')" name="show" >Show</button> This is the show function defined in the .js file f ...

Using knockout to retrieve the attribute value with an onClick event

Snippet of HTML View with attribute value 'Qref'. This is the sample HTML Code for binding Currently, I have manually inputted the Qref Attribute value <!--ko if:$parent.Type == 2 --> <input type="checkbox" data-bind="attr:{id: $data ...

These constant syntax errors are really starting to drive me up the wall

I'm working on a code that starts at 10 and goes down to 1, with odd numbers being incremented by 1 and even numbers being decremented by 1. The code works fine without using ""<br />"", but when I try to line up the numbers individually my synt ...

ALSO, various criteria

function findLogicalAND(){ let result; let index; for (index = 0; index < arguments.length; index++){ result = arguments[index] && arguments[index+1]; } return result; } console.log(findLogicalAND(true, true, false, false)); I want to r ...

Having trouble decoding JSON data using PHP

I am currently attempting to parse JSON data for a project I am working on, but I am facing some issues. The code I previously used is not functioning properly with this particular API. Below is the code snippet: <?php $json_string = file_g ...

Tips for setting up a webpacked vue.js application with an express/koa backend!

Struggling with setting up a vue.js project for easy debugging in combination with a koa server? The cross-env NODE_ENV=development webpack-dev-server --open --hot command from the webpack-simple generated configuration looks promising, but how should it b ...

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...

How can I easily activate a C# class from an asp.net webpage?

I have three labels in my asp.net page: One with a default name for filtering Another filled with a list of names to click on for new filter A third one with a list of items to be filtered The content of the second and third labels is loaded by C# code ...

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

Use markdown links instead of html hyperlinks

I encountered a scenario where I have a string formatted like this: 'Hello, my name is <a href="https://stackoverflow.com/foo/bar">foobar</a> My favorite food is <a href="https://google.com/food/pizza">pizza</a ...

Establish and define the global variable "Protractor"

In order to pass a string value from the function editPage.CreateEntity();, you can use that value in multiple test cases by assigning it to the variable entityName. You are able to retrieve the value by setting up the test case as follows: fit('Te ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...

How to manage the three states (InProgress, Success, Error) of a dropdown dynamically in AngularJS with ng-show/hide?

Currently, I have implemented a bootstrap dropdown that loads a list of countries by making an external API call. My goal is to display three different states of behavior (progress, success, error) in the dropdown using ng-show/hide. However, I am unsure h ...

eliminate elements from a PHP array

I have an array of links and another array containing specific values that I want to filter out from the list, for example: Example link 1 Example link 2 Example link 3 ... I am attempting to remove all instances of "http://www.example.com". I have trie ...

Guide on simulating an incoming http request (response) using cypress

Is there a way to mock a response for an HTTP request in Cypress? Let me demonstrate my current code: Cypress.Commands.add("FakeLoginWithMsal", (userId) => { cy.intercept('**/oauth2/v2.0/token', (req) => { ...

Retrieve data from a form on the server side using an Ajax request

I am currently working on submitting form data through an Ajax call. Here is the relevant form code: <form target="_blank" id="addCaseForm" class="form-horizontal col-md-12" action="" method="POST> <div class="form-group"> <labe ...

The Script Component is not functioning properly in next.js

While using Tiny Editor, I encountered an issue with defining a key for the editor. According to the documentation, I need to access this key through the tag <script src='address'. This method seems to work fine initially. However, when combin ...

Issue with applying CSS properties of 'top' and 'left' to a dynamically created div using

After an extensive search on both the site and the internet, I have not had any luck so far. I am dealing with a series of dynamically-generated divs using JQuery, cloned from the original HTML source. While I can manipulate the positioning properties of ...

Vue: event triggers malfunctioning and components unresponsive

I am new to Vue.js and I'm attempting to trigger an event from my grand-child component (card) to the child component (hand) and then to the parent component (main): card (emit play event) => hand (listen for play event and emit card-play event) ...

send back an error message in ajax when mysql fails

I am currently working on a login page using AJAX. When the username and password are incorrect, I want to display an error message. If the password is correct, it should redirect to another page. However, in both cases, the success function is being calle ...